How to get all class names in a namespace in Ruby?

前端 未结 4 946
挽巷
挽巷 2020-12-28 12:59

I have a module Foo, that it is the namespace for many classes like Foo::Bar, Foo::Baz and so on.

Is there an way to return al

相关标签:
4条回答
  • 2020-12-28 13:21

    This will only return the loaded constants under the given namespace because ruby uses a lazy load approach. So, if you type

    Foo.constants.select {|c| Foo.const_get(c).is_a? Class}
    

    you will get

    []
    

    but after typing:

    Foo::Bar
    

    you will get

    [:Bar]
    
    0 讨论(0)
  • 2020-12-28 13:25

    If, instead of the names of the constants, you want the classes themselves, you could do it like this:

    Foo.constants.map(&Foo.method(:const_get)).grep(Class)
    
    0 讨论(0)
  • 2020-12-28 13:25

    In short no. However, you can show all classes that have been loaded. So first you have to load all classfiles in the namespace:

    Dir["#{File.dirname(__FILE__)}/lib/foo/*.rb"].each {|file| load file}
    

    then you can use a method like Jörg W Mittag's to list the classes

    Foo.constants.map(&Foo.method(:const_get)).grep(Class)

    0 讨论(0)
  • 2020-12-28 13:29
    Foo.constants
    

    returns all constants in Foo. This includes, but is not limited to, classnames. If you want only class names, you can use

    Foo.constants.select {|c| Foo.const_get(c).is_a? Class}
    

    If you want class and module names, you can use is_a? Module instead of is_a? Class.

    0 讨论(0)
提交回复
热议问题