[英]Ruby on Rails: how do I set a variable where the variable being changed can change?
[英]Ruby on Rails: How do I set a variable to a constant, where part of the name of the constant can change?
我想要做
current_user.field = User::????????
?
哪里??????????
就是我想要的那樣
這是我想做的
Given /^"([^\"]*)" is a(?:|n) "([^\"]*)"$/ do |arg1, arg2|
cur_user = User.find(:first, :conditions => ['name = ?', arg1])
cur_user.update_attributes(:role => User::arg2.constantize)
end
雖然常量化不適用於此用途,但我確實知道它將在Object.var.constantize上下文中有效
您要解決的問題是什么? 以這種方式使用常量是一種代碼味道,如果您有一組枚舉值或要進行配置的東西,則可能應該使用ActiveHash之類的東西。
如果確實需要通過這種方式解決問題,請為此檢查const_defined?()和const_get()。 const_get()允許您對符號/字符串常量名稱進行動態值調用,而無需對其進行常量化。
采用
????????.constantize
你可以做任何事情
可以使用:
"User::#{arg2}".constantize
要么
User.const_get(arg2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.