NullVoxPopuli
NullVoxPopuli

Reputation: 65183

Ruby on Rails: how do I set a variable where the variable being changed can change?

i want to do

current_user.allow_????? = true

where ????? could be whatever I wanted it to be

I've seen it done before.. just don't remember where, or what the thing is called.

Upvotes: 0

Views: 113

Answers (2)

alex.zherdev
alex.zherdev

Reputation: 24174

foo = "bar"
current_user.send("allow_#{foo}=", true)

EDIT:

what you're asking for in the comment is another thing. If you want to grab a constant, you should use for instance

role = "admin"
User.const_get(role)  

Upvotes: 2

Jesse Wolgamott
Jesse Wolgamott

Reputation: 40277

That's a "magic method" and you implement the method_missing on your current_user object. Example from Design Patterns

#example method passed into computer builder class  
builder.add_dvd_and_harddisk  
#or     
builder.add_turbo_and_dvd_dvd_and_harddisk  

def method_missing(name, *args)  
  words = name.to_s.split("_")  
  return super(name, *args) unless words.shift == 'add'  
  words.each do |word|  
    #next is same as continue in for loop in C#  
    next if word == 'and'  
    #each of the following method calls are a part of the builder class  
    add_cd if word == 'cd'  
    add_dvd if word == 'dvd'  
    add_hard_disk(100000) if word == 'harddisk'  
    turbo if word == 'turbo'  
  end  
end  

Upvotes: 0

Related Questions