繁体   English   中英

Ruby on Rails:如何设置要更改的变量可以更改的变量?

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

我想要做

current_user.allow_????? = true

哪里????? 可能是我想要的

我以前看过它做过..只是不记得在哪里,或所谓的东西。

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

编辑:

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

role = "admin"
User.const_get(role)  

那是一个“魔术方法”,您可以在current_user对象上实现method_missing。 设计模式示例

#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  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM