有一个包含模块和类名的字符串,例如:
"Admin::MetaDatasController"
Run Code Online (Sandbox Code Playgroud)
我如何获得实际课程?
如果没有模块,以下代码可以工作:
Kernel.const_get("MetaDatasController")
Run Code Online (Sandbox Code Playgroud)
但它打破了模块:
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 >
Run Code Online (Sandbox Code Playgroud) 从拍摄前一后进行一些修改,以回应sepp2k的关于命名空间的评论,我已经实现字符串#to_class方法.我在这里分享代码,我相信它可能会被重构,特别是"i"计数器.您的意见表示赞赏.
class String
def to_class
chain = self.split "::"
i=0
res = chain.inject(Module) do |ans,obj|
break if ans.nil?
i+=1
klass = ans.const_get(obj)
# Make sure the current obj is a valid class
# Or it's a module but not the last element,
# as the last element should be a class
klass.is_a?(Class) || (klass.is_a?(Module) and i != chain.length) ? klass : nil
end
rescue NameError
nil
end
end
#Tests that should be passed.
assert_equal(Fixnum,"Fixnum".to_class)
assert_equal(M::C,"M::C".to_class)
assert_nil …Run Code Online (Sandbox Code Playgroud)