问题描述
有一个包含模块和类名称的字符串,例如:
Having a string with the module and name of a class, like:
"Admin::MetaDatasController"
我如何获得实际课程?
如果没有模块,以下代码有效:
The following code works if there's no module:
Kernel.const_get("MetaDatasController")
但它打破了模块:
ruby-1.8.7-p174 > Kernel.const_get("Admin::MetaDatasController")
NameError: wrong constant name Admin::MetaDatasController
from (irb):34:in `const_get'
from (irb):34
ruby-1.8.7-p174 >
推荐答案
如果你想要一些简单的东西来处理你的特殊情况,你可以写
If you want something simple that handles just your special case you can write
Object.const_get("Admin").const_get("MetaDatasController")
但是如果你想要更一般的东西,在 ::
上拆分字符串并一个接一个地解析名称:
But if you want something more general, split the string on ::
and resolve the names one after the other:
def class_from_string(str)
str.split('::').inject(Object) do |mod, class_name|
mod.const_get(class_name)
end
end
the_class = class_from_string("Admin::MetaDatasController")
在第一次迭代 Object
被要求提供常量 Admin
并返回 Admin
模块或类,然后在第二次迭代该模块或类被要求提供常量 MetaDatasController
,并返回该类.由于没有更多组件从该方法返回该类(如果有更多组件,它将迭代直到找到最后一个).
On the first iteration Object
is asked for the constant Admin
and returns the Admin
module or class, then on the second iteration that module or class is asked for the constant MetaDatasController
, and returns that class. Since there are no more components that class is returned from the method (if there had been more components it would have iterated until it found the last).
这篇关于在 Ruby 中按名称获取类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!