Find classes available in a Module

非 Y 不嫁゛ 提交于 2019-12-17 21:57:53

问题


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?


回答1:


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}



回答2:


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]**


来源:https://stackoverflow.com/questions/833125/find-classes-available-in-a-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!