Rails - 带有'attribute ='方法的alias_method_chain

时间:2010-01-20 17:28:32

标签: ruby-on-rails 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

我在函数定义上出错了。怎么绕过这个?

1 个答案:

答案 0 :(得分:8)

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符号处理方法名称的尾随=?没有问题。

相关问题