Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby: How can I get all the Class and/or Module objects that are a child of a Module?

Tags:

ruby

Supposing I have the following:

module A
  class B
    # ...
  end

  # ...
end

And suppose I have several different files like this, with different values of B, but all in the same module (A). From a program that require's a file that then require's each of these files, is there a way with introspection/reflection (are these different things? I'm hazy on the distinction, if so) to determine (and get objects for) each class within the module?

I've tried this, which gets me sort of close:

A.constants # => ["B"]

But I'd prefer to get back [A::B], rather than a string, so that I can then call something like singleton_methods on it, which would be useful to my program, which is attempting to map data into calls into the various subclasses' methods.

Is there some way to do this? I've been digging for answers, and found a few related things, like this or this, but nothing that's quite spot on.

like image 977
lindes Avatar asked Oct 28 '25 12:10

lindes


1 Answers

Hah! Wouldn't you know it? Just after writing this, I discovered an answer that seems to work for me:

A.constants.collect{|k| A.const_get(k)}.select {|k| k.is_a?(Class)} # => [A::B]

Sweet, that was easy, once I put the right pieces together. :)

like image 64
lindes Avatar answered Oct 30 '25 05:10

lindes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!