我可以用两个冒号访问红宝石的顶级命名空间中的类名的前面,例如::AmbiguousClass
如何通过Ruby中的元编程访问顶级命名空间?
我怎么能做到这一点通过元编程?
我有很多的方法(超过5)验证,并返回给定的类,其中包括所有这样一行:
player = ::Player.find_by(uuid: input.player_uuid)
我想做出更一般这样我就可以在课堂上通过uuid找到并将所有这些方法合并为一个。这是我已经试过:
def validate_and_return(model_name)
uuid_attr = "#{model_name}_uuid".to_sym
return unless input.respond_to?(uuid_attr)
klass = ::model_name.to_s.captialize.constantize
instance = klass.find_by(uuid: input.send(uuid_attr))
# validate instance
end
这并不工作 - 它返回一个语法错误:
Class: <SyntaxError>
Message: <"/home/dax/programming/xxx/lib/bus/converters/converter.rb:48: syntax error, unexpected tIDENTIFIER, expecting tCONSTANT
什么是“输入”? –
输入是一个绑定对象(https://github.com/neopoly/bound/),与openstruct相似的行为 – dax
'klass = Object.const_get(model_name.capitalize)'工作吗? – Stefan