简体   繁体   English

Rails:如何以类似于alias_method_chain的方式来装饰属性?

[英]Rails: How to decorate an attribute in a similar fasion to alias_method_chain?

In rails, this is a common pattern: 在rails中,这是一种常见的模式:

def foo_with_feature
  add_feature_to foo_without_feature
end

alias_method_chain :foo, :feature

I want to do this but with an attribute, whose getter method is not defined and will be done on-the-fly with method_missing , see Why alias_method fails in Rails model 我要执行此操作,但要使用一个属性,该属性的getter方法未定义,并且将通过method_missing即时完成,请参阅为什么alias_method在Rails模型中失败

How can I decorate an attribute getter that hasn't been set? 如何装饰尚未设置的属性获取器?

Simply access the attribute directly like so: 只需直接访问属性即可,如下所示:

def fooattr_raw
  self.attributes["fooattr"]
end

def fooattr
  add_feature_to fooattr_raw
end

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

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