Find classes available in a Module

后端 未结 2 1556
说谎
说谎 2020-12-13 03:08

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:



        
相关标签:
2条回答
  • 2020-12-13 03:49

    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]**
    
    0 讨论(0)
  • 2020-12-13 03:57

    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}
    
    0 讨论(0)
提交回复
热议问题