如何在Ruby中将文件作为模块的一部分?

时间:2017-09-30 20:19:07

标签: ruby module namespaces

我有一个文件SomethingClass.rb,如下所示:

class SomethingClass
  def initialize
    puts "Hello World"
  end
end

我想require文件SomethingClass.rb,并SomethingClass部分模块SomethingModule ,无需更改文件。

另外,我想避免在该模块之外的SomethingClass部分命名空间。换句话说,我想require该文件,我的应用程序的其余部分不应该改变SomethingModule将被定义的事实。

这不起作用(我假设因为require范围内执行Kernel):

module SomethingModule
  require './SomethingClass.rb'
end

这可以在Ruby中使用吗?

1 个答案:

答案 0 :(得分:1)

在不更改您的类文件的情况下,根据我收集的内容,只有一种黑客方法可以执行此操作 - 请参阅Load Ruby gem into a user-defined namespaceHow to undefine class in Ruby?

但是我想如果你允许自己修改类文件,那就容易多了。可能最简单的做法是将原始类名设置为肯定没有名称冲突的东西,例如:

class PrivateSomethingClass
  def initialize
    puts "Hello World"
  end
end

module SomethingModule
  SomethingClass = PrivateSomethingClass
end

现在,您已在全局命名空间中定义了SomethingModule::SomethingClass但未定义SomethingClass

另一种方法是使用工厂方法和anonymous class

class SomethingClassFactory
  def self.build
    Class.new do
      def initialize
        "hello world"
      end
    end
  end
end

module SomethingModule
  SomethingClass = SomethingClassFactory.build
end