模块中的alias_method_chain

时间:2014-07-15 16:34:04

标签: ruby-on-rails ruby

我想要一个模块alias_method_chain来自它所包含的类的方法。我是这样写的:

module MyModule
  self.included(base)
    base.class_eval do
      alias_method_chain :perform, :chain
    end
  end
  def perform_with_chain(opts)
    #Do some stuffs
    perform_without_chain(opts)
    #Do some other stuffs
  end
end

class SomeClass
  include MyModule
  def perform(opts)
  end
end

但是这会引发错误,因为当包含该模块时,perform中尚未定义SomeClass方法:

in `alias_method': undefined method `perform' for class `SomeClass' (NameError)

如何编写此模式以使别名链完全有效?

1 个答案:

答案 0 :(得分:2)

在定义perform后加入。

class SomeClass
  def perform(opts)
  end
  include MyModule
end