How to get the submodules of a ruby module

I needed to be able to find out what modules were defined inside a particular ruby module. Kinda like wanting to find out what child namespaces exist for a module. It’s probably more easily explained with an example. Given the following construct…

module A
  module B; end
  module C; end
  module D
    module E; end
  end
end

…I wanted to be able to ask A what submodules are defined within it and get the following answer:

[A::B, A::C, A::D]

(btw: I don’t want to see E in the list as it is not a direct child of A).

So… since the Module class doesn’t provide anything to support doing that, I wrote a method that does it for me. Here’s the monkey-patch:

class Module
  def submodules
    modules = []
    self.constants.each do |const|
      temp_const = self.const_get(const)
      modules << temp_const if temp_const.class == Module
    end
    modules
  end
end

With that, you can now call the submodules method against any module and you’ll be returned an array of modules!

This entry was posted in Example Code, Ruby and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>