![](/img/trans.png)
[英]Ruby on Rails: how do I set a variable where the variable being changed can change?
[英]Ruby on Rails: How do I set a variable to a constant, where part of the name of the constant can change?
我想要做
current_user.field = User::????????
?
哪里??????????
就是我想要的那样
这是我想做的
Given /^"([^\"]*)" is a(?:|n) "([^\"]*)"$/ do |arg1, arg2|
cur_user = User.find(:first, :conditions => ['name = ?', arg1])
cur_user.update_attributes(:role => User::arg2.constantize)
end
虽然常量化不适用于此用途,但我确实知道它将在Object.var.constantize上下文中有效
您要解决的问题是什么? 以这种方式使用常量是一种代码味道,如果您有一组枚举值或要进行配置的东西,则可能应该使用ActiveHash之类的东西。
如果确实需要通过这种方式解决问题,请为此检查const_defined?()和const_get()。 const_get()允许您对符号/字符串常量名称进行动态值调用,而无需对其进行常量化。
采用
????????.constantize
你可以做任何事情
可以使用:
"User::#{arg2}".constantize
要么
User.const_get(arg2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.