[英]Rails: How to decorate an attribute in a similar fasion to alias_method_chain?
[英]Rails - alias_method_chain with a 'attribute=' method
當它被包含在內時,我想通過模塊在模型的方法上“添加”一些代碼。 我想我應該使用alias_method_chain,但我不知道如何使用它,因為我的'別名方法'是以'='符號結尾的方法之一:
class MyModel < ActiveRecord::Base
def foo=(value)
... do stuff with value
end
end
所以這就是我的模塊現在看起來的樣子:
module MyModule
def self.included(base)
base.send(:include, InstanceMethods)
base.class_eval do
alias_method_chain 'foo=', :bar
end
end
module InstanceMethods
def foo=_with_bar(value) # ERROR HERE
... do more stuff with value
end
end
end
我在函數定義上出錯了。 怎么繞過這個?
alias_method_chain
是一個簡單的兩行方法:
def alias_method_chain( target, feature )
alias_method "#{target}_without_#{feature}", target
alias_method target, "#{target}_with_#{feature}"
end
我想你想要的答案就是在這種情況下簡單地讓兩個alias_method
調用你自己:
alias_method :foo_without_bar=, :foo=
alias_method :foo=, :foo_with_bar=
你會像這樣定義你的方法:
def foo_with_bar=(value)
...
end
Ruby符號處理尾隨=
和?
方法名稱沒有問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.