2012-05-30 35 views
1

重寫我有一個類層次結構,如下:調用父類的構造時初始化由包括模塊

class Tree 
    def initialize(id, value) 
    @id, @value = id, value 
    end 
end 

class Entity < Tree 

    include Mongoid::Document 

    def initialize(id, value) 
    # Do some stuff... 
    super(id, value) 
    end 

end 

但是,調用superEntity#initialize方法中調用initialize方法位於Mongoid::Document,而不是一個父類Tree

如何在Mongoid::Document模塊已包含之後,從Entity#initialize正文中調用Tree#initialize方法?

回答

4

這就是Ruby的工作原理。當你包含一個模塊時,ruby隱式地創建一個匿名類,並將它放在方法查找隊列中當前的上方。

也打電話給Entity.ancestors將在列表中顯示Mongoid::Document

有一個偉大的書,我可以推薦:Metaprogramming Ruby通過Paolo Perotta

而且,這裏是a forum thread on a similar topic explaining super stuff

更新:

如果避免調用模塊構造器是你想要的這裏是一個可能的伎倆

class Entity < Tree 

    def initialize(id, value) 
    # Do some stuff... 
    # initialize first 
    super(id, value) 
    # and after that - extend 
    extend Mongoid::Document 
    end 

end 

此方法未在模塊上運行self.included。如果你需要保留這個功能,仍然不是runnin模塊的初始化工具,本徵類可以在init中使用:

class Entity < Tree 

    def initialize(id, value) 
    # Do some stuff... 
    # initialize first 
    super(id, value) 
    # and after that - include into eigenclass 
    class << self 
     include Mongoid::Document 
    end 
    end 

end 
+0

謝謝你使這個更清晰。但我的問題是:我如何從Entity#initialize方法的主體訪問Tree#initialize方法? – user2398029

+0

檢查更新。包含模塊的方式可能不同。 –