views:

43

answers:

3

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 use, I do know that it would work In Object.var.constantize context

A: 

Use

????????.constantize

you can do any thing

Almost, I found a typo in my post. I meant User:: not User.While, what you have will work in most cases, it does't for mine T_T
DerNalia
+1  A: 

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

Winfield
Smells good to me. I think the problem he is trying to solve is well illustrated too (if you know cucumber).
Marc-André Lafortune
Hey Marc, that example was added later. Given this example, something like ActiveHash feels like a better way to define the set of Roles than constant Role IDs: http://github.com/zilkey/active_hash
Winfield
A: 

Either use:

"User::#{arg2}".constantize

or

User.const_get(arg2)
Marc-André Lafortune