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

前端 未结 2 2011
深忆病人
深忆病人 2021-01-05 09:28

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 i

2条回答
  •  余生分开走
    2021-01-05 09:56

    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).

提交回复
热议问题