Ruby 在扩展时调用模块方法

Ruby Invoking Module Method On Extend

给定一个基本的 ruby class 和模块,有没有办法在扩展 class 的实例后立即从模块调用方法?

class Dog 
  def initialize(name)
    @name = name 
  end 
end

module Speech
  def say_name
    puts @name
  end
  # call to method in module ?
  say_name
end

fido = Dog.new('fido')
fido.extend Speech    => *'fido'*

我知道 'included' 方法在包含模块时有点像回调,但我希望扩展有类似的东西。

这是使用方法 extend_object 的一个技巧。

Extends the specified object by adding this module’s constants and methods (which are added as singleton methods). This is the callback method used by Object#extend.

class Dog 
  def initialize(name)
    @name = name 
  end 
end

module Speech
  def Speech.extend_object(o)
    super
    puts o.say_name
  end

  def say_name
    @name
  end
end

fido = Dog.new('fido')
fido.extend Speech # 'fido'