3

Is it possible to know all the classes defined inside a module in ruby.

module A
  class Klass
  end
  class Klass1
  end
end

Is there any ruby introspection method to get all the classes defined in module A?

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
Rohan Pujari
  • 788
  • 9
  • 21
  • Does this answer your question? [Find classes available in a Module](https://stackoverflow.com/questions/833125/find-classes-available-in-a-module) – ggorlen Dec 19 '22 at 02:45

1 Answers1

11

Here is one way

module A
  class Klass
  end
  X = 10
  module B;end
end

# Just to list the class(s) defined inside A
A.constants.select { |k| A.const_get(k).instance_of? Class } # => [:Klass] 

Nice post to do the same in recursively.

Community
  • 1
  • 1
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
  • @Max You are right `instance_of?` came into mind on the first place. So used it.. :-) – Arup Rakshit Jun 17 '14 at 15:25
  • Also doesn't work on modules/ classes etc. that have not yet been loaded. – Dennis Nov 02 '17 at 15:00
  • @Dennis That is another problem domain. Constant loading in Ruby. – Arup Rakshit Nov 02 '17 at 16:57
  • @ArupRakshit as this is clearly a dependency, it's worth noting. – Dennis Nov 02 '17 at 17:00
  • @Dennis I don't know what you mean here. Can you try in IRB? Where are you testing this? What is not working? Any sample code to examine it? – Arup Rakshit Nov 02 '17 at 17:01
  • @ArupRakshit if you put your sample code of `module A` in a separate file (make sure it's not loaded via require before calling constants) ruby does not know about the contents of the file, calling constants will not load the file or make the module inside visible for you. – Dennis Nov 29 '17 at 15:15
  • @Dennis Ok then Ruby got changed probably a lot in that case from 2014. – Arup Rakshit Nov 29 '17 at 15:52