0

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 Answers 2

2
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)  
Sign up to request clarification or add additional context in comments.

2 Comments

this is real slick. What if a want to do something like? current_user.role = User::??????
0

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  

2 Comments

I like neutrino's method above better; easier to do.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.