Home > Blockchain >  Rails Load an array of subclasses from a folder automatically
Rails Load an array of subclasses from a folder automatically

Time:07-23

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.

CodePudding user response:

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

And all files from subfolder will be autoloaded

CustomClass.descendants

returns descendants of class

  • Related