Rails - 带有“attribute=”的alias_method_chain方法
我想通过模块(当包含模型时)在模型的方法上“添加”一些代码。我认为我应该使用 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
我得到一个函数定义错误。如何解决这个问题?
I'd like to 'add on' some code on a model's method via a module, when it is included. I think I should use alias_method_chain, but I don't know how to use it, since my 'aliased method' is one of those methods ending on the '=' sign:
class MyModel < ActiveRecord::Base
def foo=(value)
... do stuff with value
end
end
So this is what my module looks right now:
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
I get an error on the function definition. How do get around this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
alias_method_chain
是一个简单的两行方法:我认为您想要的答案是在这种情况下简单地让两个
alias_method
调用自己:并且您可以像这样定义您的方法so:
Ruby 符号可以毫无问题地处理方法名称的尾随
=
和?
。alias_method_chain
is a simple, two-line method:I think the answer you want is to simply make the two
alias_method
calls yourself in this case:And you would define your method like so:
Ruby symbols process the trailing
=
and?
of method names without a problem.