从内部包含模块访问类

时间:2013-12-18 23:47:23

标签: ruby

我希望能够做到这一点:

class IncludingClass
  include IncludedModule
end

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

有什么想法吗?对不起,简洁。在手机上打字。无论如何,我环顾四周并且找不到这个,这对于这种可编程的语言来说似乎令人惊讶。

1 个答案:

答案 0 :(得分: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询问它们包含哪些内容,但这有点毛茸茸,而且会慢得多。