Ruby:如何干掉类似的模型属性调用

时间:2010-02-11 16:04:59

标签: ruby attributes models

我有一个User模型,其中包含许多非常相似的属性,我想列出这些属性,而不是单独输入每个属性。

所以,而不是:

"eye color: #{@user.his_eye_color}"
"hair color: #{@user.his_hair_color}"
"height: #{@user.his_height}"
"weight: #{@user.his_weight}"
...

"eye color: #{@user.her_eye_color}"
"hair color: #{@user.her_hair_color}"
"height: #{@user.her_height}"
"weight: #{@user.her_weight}"
...

我想做一个块或什么的(Proc?Lambda?仍然不清楚那些是什么......):

['eye color','hair color','height','weight',...].do |stat|
   "#{stat}: #{@user.her_(stat.underscore)}"
end

['eye color','hair color','height','weight',...].do |stat|
   "#{stat}: #{@user.his_(stat.underscore)}"
end

我知道我上面写的是神秘的,神奇的,完全错误的(@user.his_(stat.underscore)部分),但是我能做到这一点是什么意思?我基本上需要动态调用我的Model的属性,但我不确定如何做到这一点......

任何帮助都会非常感激!

2 个答案:

答案 0 :(得分:5)

['eye color','hair color','height','weight',...].do |stat|
   "#{stat}: #{ @user.send(:"her_#{stat.tr(" ","_")}") }"
end

['eye color','hair color','height','weight',...].do |stat|
   "#{stat}: #{ @user.send(:"his_#{stat.tr(" ","_")}") }"
end

这应该有效。您始终可以使用send来调用对象上的方法,并将该方法名称动态生成为字符串

答案 1 :(得分:2)

如果您在Rails中使用ActiveRecord,您还可以使用Object#[]方法动态获取属性值

['eye color','hair color','height','weight',...].do |stat|
   "#{stat}: #{ @user[ "her_#{ stat.underscore }"]}"
end
相关问题