Ruby on Rails:如何设置变量,变量变量可以改变?

时间:2010-07-15 13:13:03

标签: ruby-on-rails ruby

我想做

current_user.allow_????? = true

?????可以是我想要的任何东西

我以前见过它......只是不记得在哪里,或者叫什么东西。

2 个答案:

答案 0 :(得分:2)

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

编辑:

你在评论中要求的是另一回事。如果你想获取一个常量,你应该使用例如

role = "admin"
User.const_get(role)  

答案 1 :(得分:0)

这是一个“神奇的方法”,你在current_user对象上实现method_missing。来自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