查找模块中可用的类

时间:2022-08-14 20:29:17

I have a module MyModule. I dynamically load classes into it. How can I get a list of the classes defined within its namespace?

我有一个模块MyModule。我动态地将类加载到其中。如何获得在其名称空间中定义的类的列表?

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".

我应该说,每个f都包含“类Foo;结束”。

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

您也可以这样想:在Rails中,如何程序化地找到在ActiveRecord模块中定义的所有类?

1 个解决方案

#1


101  

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}

#1


101  

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}