我不相信模塊跟蹤包含它們的內容。但是,當他們被包含在內時,他們會觸發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
包括哪些但這是一種毛茸茸的,並會慢得多。
那真的很酷。不確定它會在我的情況下工作,但它是一個有趣的解決方案。謝謝! – Sasha