Mike Belyakov Mike Belyakov - 6 months ago 10
Ruby Question

How to find the modules or classes that include a module?

There is a good trick which helps to find inherited subclasses:

class SubClasses

@@subclasses ||= []

def self.inherited subclass
@@subclasses << subclass
end

def self.subclasses
@@subclasses
end
end


Also, I found it useful to find modules included in child classes with
Foo.included_modules
.

But it is unavailable on
Module
. How I can fetch all classes which include the module? Is it possible?

UPDATE

Solved!

Getting a list of classes that include a module

Answer

To monitor when a module is included in another module or a class, use the included hook:

module Parent
  class << self
    attr_reader :includers
  end

  def self.included(base)
    @includers ||= []
    @includers << base.name
  end
end