我现在有两个班,每个延伸的不同的模块:
class Example1
def initialize
extend TopModule:SubModule1
end
end
class Example2
def initialize
extend TopModule:SubModule2
end
end
代替具有与每个其自身的模块延长两个类的,是有可能建立一个单一的类,然后在对象级别扩展模块?
我已经添加了模块的名称和传递一个对象的构造函数,但与代码抱怨。
class Example
def initialize (module)
self.send("extend TopModule::#{module}"
end
end
object = Example.new('Submodule1')
NoMethodError:
undefined method `extend TopModule::SubModule1' for #<Example:0x00000000057c8198>
总体问题:比方说,我有N个对象(他们都应该来自同一类,但每个对象都必须有它自己的模块)。什么是有这个能力的最佳方法?
更新的答案!
module TopModule
module SubModule1
def hello
puts "Hello from #1"
end
end
end
module TopModule
module SubModule2
def hello
puts "Hello from #2"
end
end
end
class Example
def initialize(mod)
extend TopModule.const_get(mod)
end
end
Example.new("SubModule1").hello
# => Hello from #1
Example.new("SubModule2").hello
# => Hello from #2
你可能是在错误的方式,并迫使你找到一个“好”的解决方案。 qazxsw POI
But here it is.