How can I iterate through all of the Models in my rails app?

后端 未结 5 2146
天命终不由人
天命终不由人 2021-02-08 17:51

I would like to be able to iterate over and inspect all the models in my rails app. In pseudo-code it would look something like:

rails_env.models.each do |model|         


        
5条回答
  •  走了就别回头了
    2021-02-08 17:55

    I tried implementing the above solutions under Rails 5 and they didn't quite work. Here's a solution which finds all models which starts with "page_" (or any other prefix; just specify that):

    def self.page_models(prefix = "page")
        models = []
        folder = File.join(Rails.root, "app", "models")
        Dir[File.join(folder, "*")].each do |filename|
         if filename =~ /models\/#{prefix}/
           klass = File.basename(filename, '.rb').camelize.constantize
           models << klass
         end
        end
        return models
    end
    

提交回复
热议问题