我有一个文件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中使用吗?
答案 0 :(得分:1)
在不更改您的类文件的情况下,根据我收集的内容,只有一种黑客方法可以执行此操作 - 请参阅Load Ruby gem into a user-defined namespace和How 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