Find classes available in a Module

If you're on rails, you need to access the constants first for them to show up, because they're lazyly loaded.

MyModule::NotAClass = "not a class"

MyModule.constants => [:NotAClass]

MyModule::AClass => :AClass # Access class for it to be autoloaded

MyModule.constants => [:AClass, :NotAClass]

# Now, select the constants which are class instances

MyModule.constants
        .map(&MyModule.method(:const_get))
        .select { |constant| constant.is_a? Class} 

 => [MyModule::AClass]**

Classes are accessed through constants. Classes defined within a module are listed as constants in that module. So you just need to choose the constants that refer to classes.

MyModule.constants.select {|c| MyModule.const_get(c).is_a? Class}

If you'd like to get all classes in a module recursively, you can do something like

def get_classes(mod)
  mod.constants.map do |c|
    const = mod.const_get(c)
    if const.is_a? Class
      const
    elsif const.is_a? Module
      get_classes(const)
    else
      next
    end
  end.flatten
end

Then, given some module structure like:


module MyModule
  module Submodule1
    class Class1
    end
  end

  module Submodule2
    class Class2
    end
  end
end

the output looks like:

puts get_classes(MyModule)

# => MyModule::Submodule1::Class1
# => MyModule::Submodule2::Class2