Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you find all modules and classes within a module, recursively?

Tags:

ruby

If you have:

module A
  class B
  end
end

You can find B and similar classes via A.constants. However, in Ruby 1.9.3, you cannot get B if it is within another module. In Ruby 1.8.7 you can.

module A
  module Aa
    class B
    end
  end
end

How do you get B from the first level of A? What I would like as output is an array of constants, which include all classes like B, but anywhere within the module A.

like image 630
Jade Avatar asked Mar 24 '12 00:03

Jade


1 Answers

class Module
  def all_the_modules
    [self] + constants.map {|const| const_get(const) }
      .select {|const| const.is_a? Module }
      .flat_map {|const| const.all_the_modules }
  end
end

A.all_the_modules
# => [A, A::Aa, A::Aa::B]

This code will break if you do have circular namespaces, aka A::Aa::B.const_set(:A, A).

like image 171
Reactormonk Avatar answered Oct 20 '22 00:10

Reactormonk