3

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

Community
  • 1
  • 1
Mike Belyakov
  • 1,355
  • 1
  • 13
  • 24
  • I almost marked this question as a duplicate of the one you linked to, but that question starts with the answer to yours and goes on to something more complicated, so yours does a better job of just asking what's in the title. – Dave Schweisguth May 10 '16 at 00:16

1 Answers1

4

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
Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
  • Thank you! It is much more right and fast way, than look throw all `ObjectSpace` :) So now I know 2 ways – Mike Belyakov May 10 '16 at 00:16
  • Mike, Ruby wouldn't work up a sweat looking through all the classes. For Ruby 2.3.0, `ObjectSpace.each_object(Class).to_a.size #=> 533`. btw, I like the answer you are referring to at the link. Good answer, @Dave. – Cary Swoveland May 10 '16 at 05:43