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.
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With