Ruby on Rails:如何将变量设置为常量,常量名称的一部分可以更改?
我想要做
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
虽然constantize不能用于此用途,但我知道它可以在Object.var.constantize上下文中工作
使用:
"User::#{arg2}".constantize
要么
User.const_get(arg2)
你想解决的问题是什么? 以这种方式使用常量是一种代码气味,如果你有一组Enumeration值或者需要配置的东西,你可能应该使用像ActiveHash这样的东西。
如果您确实需要以这种方式解决问题,请查看const_defined?()和const_get()。 const_get()将允许您对符号/字符串常量名称执行动态值调用,而不对其进行常量化。
使用
????????.constantize
你可以做任何事情