Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find classes available in a Module

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?

like image 643
joshuaxls Avatar asked May 07 '09 06:05

joshuaxls


People also ask

How do I see classes in Python?

To get the class name of an instance in Python: Use the type() function and __name__ to get the type or class of the Object/Instance. Using the combination of the __class__ and __name__ to get the type or class of the Object/Instance.

How do I list all methods in a Python module?

You can use dir(module) to see all available methods/attributes.

CAN module contain classes?

A module can have zero or one or multiple classes. A class can be implemented in one or more . py files (modules). But often, we can organize a set of variables and functions into a class definition or just simply put them in a .

Can Python modules contain classes?

A Python module is a file containing Python definitions and statements. A module can define functions, classes, and variables. A module can also include runnable code. Grouping related code into a module makes the code easier to understand and use.


2 Answers

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| MyModule.const_get(c).is_a? Class} 
like image 58
Chuck Avatar answered Oct 05 '22 21:10

Chuck


If you're on rails, you need to access the constants first for them to show up, because they're lazyly loaded.

MyModule::NotAClass = "not a class"  MyModule.constants => [:NotAClass]  MyModule::AClass => :AClass # Access class for it to be autoloaded  MyModule.constants => [:AClass, :NotAClass]  # Now, select the constants which are class instances  MyModule.constants         .map(&MyModule.method(:const_get))         .select { |constant| constant.is_a? Class}    => [MyModule::AClass]** 
like image 21
cesartalves Avatar answered Oct 05 '22 19:10

cesartalves