Mat*_*att 11 ruby metaprogramming
我在Ruby中做了一些元编程,我需要在模块中动态生成一个兄弟类.这样做,我想在模块上调用const_set,但我不知道在运行时调用哪个模块常量.一个例子:
鉴于课程
Foo::Bar::Baz
Foo::Quox::Quack
Run Code Online (Sandbox Code Playgroud)
我想能够调用这样的函数(在这里过于简化):
def generate_from klass
mod = klass.enclosing_module # <- THIS LINE is the one I need to figure out
mod.const_set("GeneratedClassName", Class.new)
end
Run Code Online (Sandbox Code Playgroud)
在调用时Baz,我最终想要的是一个定义为的新类
Foo::Bar::GeneratedClassName
Run Code Online (Sandbox Code Playgroud)
我想要一个嘎嘎
Foo::Quox::GeneratedClassName
Run Code Online (Sandbox Code Playgroud)
我知道的唯一方法是拆分klass.name,然后在这些字符串上反复调用const_get,并进行实例化.有谁知道更优雅的方式?
Mic*_*ohl 18
这应该让你走上正轨:
module Foo
module Bar
class Baz
def initialize
@nesting = Module.nesting
end
def enclosing_module
@nesting.last
end
end
end
end
puts Foo::Bar::Baz.new.enclosing_module #=> Foo
Run Code Online (Sandbox Code Playgroud)
相关文件:
http://ruby-doc.org/core/classes/Module.html#M000441