NullVoxPopuli
NullVoxPopuli

Reputation: 65083

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

Upvotes: 0

Views: 325

Answers (3)

Marc-André Lafortune
Marc-André Lafortune

Reputation: 79552

Either use:

"User::#{arg2}".constantize

or

User.const_get(arg2)

Upvotes: 0

Winfield
Winfield

Reputation: 19145

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

Upvotes: 1

Sachin R
Sachin R

Reputation: 11876

Use

????????.constantize

you can do any thing

Upvotes: 0

Related Questions