Rails - 具有 'attribute=' 方法的 alias_method_chain
-
21-09-2019 - |
题
我想通过模块(当包含模型时)在模型的方法上“添加”一些代码。我认为我应该使用 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 符号处理尾随 =
和 ?
方法名称没有问题。
不隶属于 StackOverflow