views:

63

answers:

1

I really must be missing something here. Say I have a module MyModule. I dynamically load classes into it. How can I get a list of the classes defined within its namespace?

Example:

def load_plugins
  Dir.glob(File.dirname(__FILE__) + '/plugins/*.rb') do |f|
    MyModule.class_eval File.read(f)
  end

  # now how can I find the new classes I've loaded into MyModule?
end

I should say that each f contains something like "class Foo; end".

You can also think of it like this: in rails, how could I programatically find all classes defined within the ActiveRecord module?

+3  A: 

Classes are accessed through constants. Classes defined within a module are listed as constants in that module. So you just need to choose the constants that refer to classes.

MyModule.constants.select {|c| Class === MyModule.const_get(c)}
Chuck
Awesome. Thanks.
joshuaxls
One thing: why do you use that test instead of "MyModule.const_get(c).is_a? Class"? I'm not familiar with using "===" like that.
joshuaxls
No compelling reason. The === version was just more readable for me. Using is_a? would work just as well.
Chuck