mhe*_*xon 112 ruby ruby-on-rails-3
我有一个类的名称,我想创建该类的实例,以便我可以遍历该类的架构中存在的每个rails属性.
我该怎么做呢?
Wes*_*Wes 205
在rails中你可以做到:
clazz = 'ExampleClass'.constantize
Run Code Online (Sandbox Code Playgroud)
在纯红宝石:
clazz = Object.const_get('ExampleClass')
Run Code Online (Sandbox Code Playgroud)
与模块:
module Foo
class Bar
end
end
Run Code Online (Sandbox Code Playgroud)
你会用的
> clazz = 'Foo::Bar'.split('::').inject(Object) {|o,c| o.const_get c}
=> Foo::Bar
> clazz.new
=> #<Foo::Bar:0x0000010110a4f8>
Run Code Online (Sandbox Code Playgroud)
edg*_*ner 13
在Rails中非常简单:使用 String#constantize
class_name = "MyClass"
instance = class_name.constantize.new
Run Code Online (Sandbox Code Playgroud)
module One
module Two
class Three
def say_hi
puts "say hi"
end
end
end
end
one = Object.const_get "One"
puts one.class # => Module
three = One::Two.const_get "Three"
puts three.class # => Class
three.new.say_hi # => "say hi"
Run Code Online (Sandbox Code Playgroud)
在 ruby 2.0 和可能更早的版本中,Object.const_get将递归地对像Foo::Bar. 上面的例子是提前知道命名空间并突出了const_get可以直接在模块上调用而不是专门在 上调用的事实Object。
试试这个:
Kernel.const_get("MyClass").new
Run Code Online (Sandbox Code Playgroud)
然后遍历对象的实例变量:
obj.instance_variables.each do |v|
# do something
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
50267 次 |
| 最近记录: |