Ruby: How can I get all the objects of a class and / or module that are children of the module?

Suppose I have the following:

module A
  class B
    # ...
  end

  # ...
end

And suppose I have several different files, like this one, with different B values, but all in one module (A). From the program in which requirethere is a file, which then requireeach of these files has, is there an introspection / reflection method (are these different things? Am I distinguished if this is so) to determine (and get objects for) each class in the module?

I tried this, which closed me:

A.constants # => ["B"]

But I would prefer to return [A::B], rather than a string, so that I can call something like singleton_methodson it, which would be useful for my program, which is trying to map data into calls to methods of various subclasses.

? , this , .

+3
2

! ? , , , , :

A.constants.collect{|k| A.const_get(k)}.select {|k| k.is_a?(Class)} # => [A::B]

, , .:)

+5

, , :

    def all_classes_in_module_except_base(module_class)
      Dir["#{Rails.root}/app/domains/#{module_class.to_s.underscore}s/*.rb"].each { |file| load file }
      module_class.constants.collect { |k| module_class.const_get(k) }.select { |k|
        k.is_a?(Class) && k.name.demodulize != "Base"
      }
    end
0

Source: https://habr.com/ru/post/1790377/


All Articles