如何在模块中定义self.included,以便它通过其包含/扩展模块传递给后续的include / extends

时间:2012-11-08 02:52:31

标签: ruby

我有很多模块,当它们被包含在内时我想让它们调用一个'包含'的函数..这个函数对于所有这些函数都是一样的..我希望能够因此包含它在一个模块中运行并让所有这些子模块包括..这是一个人为的例子,但我需要类似......

module Humanable
  def self.extended(klass)
    klass.instance_eval do
      define_method :included do |base|
        puts 'I was just included into the Person Class'
      end
    end
  end
end

module Personable
  extend Human
end

class Person
  include Personable
end

当Person包含Personable ..时,将来自Humanable模块的字符串放入..这不起作用,但希望你明白我该如何实现呢?

1 个答案:

答案 0 :(得分:0)

答案似乎是:

module Humanable
  def self.extended(klass)
    klass.define_singleton_method :included do |base|
      puts 'hello'
    end
  end
end

module Personable
  extend Humanable # does **not** puts 'hello'
end

class Person
  include Personable # puts 'hello'
end