2012-11-08 40 views
0

我有一些模塊,當它們包含時,我希望它們調用一個'included'函數。 。這個函數對於所有這些都是一樣的。我希望能夠在模塊中包含這個包含的函數,並且所有這些子模塊都包含這個。這是一個人爲的例子,但我需要類似的東西。 ...如何在模塊中定義self.included,以便它通過其包含的/擴展模塊傳遞給隨後的包含/擴展

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 

哪裏人時,包括Personable..it把字符串從Humanable模塊。這不工作,但希望你的想法我怎麼能做到這一點?

+0

你說「所有子模塊*包括*它」在您的標題,但隨後在你的榜樣,你* *擴展它。你的意思是? –

+0

我試圖澄清..原諒混淆不知道如何將它..這個例子可能是最好的地方,我想包括Personable內Person執行puts'我只是包括'行...但不是在Personable擴展Human時執行該行。 – Inc1982

+0

找出我需要的答案..謝謝你的幫助Andrew – Inc1982

回答

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