2013-12-18 208 views
0

我希望能夠做到這一點:訪問類包括模塊

class IncludingClass 
    include IncludedModule 
end 

module IncludedModule 
    self.parent_class # => IncludingClass, I wish 
end 

任何想法?對不起,爲簡潔起見。在手機上輸入這個。無論如何,我環顧四周,一直未能找到這個,這對於這樣一個可編程語言來說似乎令人驚訝。

回答

1

我不相信模塊跟蹤包含它們的內容。但是,當他們被包含在內時,他們會觸發MyModule.included(SomeClass)方法作爲回調,因此您可以跟蹤自己。

module IncludedModule 

    # Array to store included classes 
    @@included_classes = [] 

    # Called when this module is included. 
    # The including class is passed as an argument. 
    def self.included(base) 
    @@included_classes << base 
    end 

    # Getter for class variable 
    def self.included_classes 
    @@included_classes 
    end 
end 

# Include the module 
class IncludingClass 
    include IncludedModule 
end 

# Ask the module what included it. 
puts IncludedModule.included_classes #=> [IncludingClass] 

有可能也是抓取聲明的所有課程,並要求他們的方式,他們通過SomeClass.included_modules包括哪些但這是一種毛茸茸的,並會慢得多。

+0

那真的很酷。不確定它會在我的情況下工作,但它是一個有趣的解決方案。謝謝! – Sasha