开发者

Ruby on Rails: How do I set a variable to a constant, where part of the name of the constant can change?

I want to do

current_user.field = User::?????????

Where ?????????? would be whatever I wanted it to be

This what I'm trying to do

Given /^"([^\"]*)" is a(?:|n) "([^\"]*)"$/ do |arg1, arg2|
  cur_user = User.find(:first, :conditions => ['name = ?', arg1])
  cur_user.update_attributes(:role => User::arg2.constantize)
end

While constantize does't work for this开发者_JAVA百科 use, I do know that it would work In Object.var.constantize context


What's the problem you're trying to solve? Using constants this way is a code smell, you should probably be using something like ActiveHash if you've got a set of Enumeration values or something that's configuration to walk through.

If you do need to solve your problem this way, check out const_defined?() and const_get() for this. const_get() will allow you to do a dynamic value call on a symbol/string constant name without constantizing it.

http://ruby-doc.org/core/classes/Module.html#M001689


Either use:

"User::#{arg2}".constantize

or

User.const_get(arg2)


Use

????????.constantize

you can do any thing

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜