views:

38

answers:

2

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.

+2  A: 
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)  
neutrino
this is real slick. What if a want to do something like?current_user.role = User::??????
DerNalia
http://stackoverflow.com/questions/3256171/ruby-on-rails-how-do-i-set-a-variable-to-a-constant-where-part-of-the-name-of-t
DerNalia
A: 

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  
Jesse Wolgamott
I like neutrino's method above better; easier to do.
Jesse Wolgamott
actually `method_missing` is a different thing altogether. the author wants to call a method of a variable name, and this answer shows a way how to make the object respond to such calls.
neutrino