1

I am working with heritage on rails models. I have this class on the file:

models/custom_class.rb


class CustomClass < ApplicationRecord
    def self.available_from_my_class
        [
            CustomClasses::CustomClassA,
            CustomClasses::CustomClassB,
            CustomClasses::CustomClassC,
            (...)
        ]
    end

    def self.type
        raise "You must override this method in each model inheriting from CustomClass"
    end
end

That works fine and loads an array, but I have to declare each subclass manually.

Then I have a folder with that classes:

models/custom_classes/custom_class_a.rb
models/custom_classes/custom_class_b.rb
models/custom_classes/custom_class_c.rb

With the code that inheritance in each:

class CustomClasses::CustomClassA < CustomClass
    def self.to_s
        "Custom Class A"
    end


    def self.type
        "CustomClassA"
    end
end

I would like to know how could I load an array of all the subclasses on the folder models/custom_classes/ automatically on available_from_my_class at models/custom_class.rb

I tried:


class CustomClass < ApplicationRecord
    def self.available_from_my_class
        [
            # Load all the Subclasses from the folder custom_classes
            CustomClasses::Subclasses.all
            # got the error uninitialized constant  CustomClasses::Subclasses

        ]

    end

end

But didn`t work.

Diogo Wernik
  • 586
  • 8
  • 24

1 Answers1

1
config.autoload_paths += Dir[Rails.root.join('app', 'models', '**/')]

And all files from subfolder will be autoloaded

CustomClass.descendants

returns descendants of class

mechnicov
  • 12,025
  • 4
  • 33
  • 56
  • thanks, I will try that. Do I need to use both, `config.autoload_paths` and `descendants method` together? – Diogo Wernik Jul 22 '22 at 13:34
  • 1
    First one autoloads constants, second returns array of subclasses – mechnicov Jul 22 '22 at 13:36
  • 1
    Thanks for replay @mechnicov, i added, `config.autoload_paths += Dir[Rails.root.join('app', 'models', '**/')]` to the file `config/development.rb`, and `CustomClass.descendants`, but it returns an empty `[]` array. – Diogo Wernik Jul 22 '22 at 16:36
  • 1
    But your answer helped me find the solution, and I found the solution on this StackOverflow question: https://stackoverflow.com/questions/5888313/ror-mymodel-descendants-returns-in-a-view-after-the-first-call – Diogo Wernik Jul 22 '22 at 16:37