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

后端 未结 5 2145
天命终不由人
天命终不由人 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 18:01

    Rails Admin uses this code (see https://github.com/sferik/rails_admin/blob/master/lib/rails_admin/config.rb, method viable_models):

    ([Rails.application] + Rails::Engine.subclasses.collect(&:instance)).flat_map do |app|
              (app.paths['app/models'].to_a + app.config.autoload_paths).collect do |load_path|
                Dir.glob(app.root.join(load_path)).collect do |load_dir|
                  Dir.glob(load_dir + '/**/*.rb').collect do |filename|
                    # app/models/module/class.rb => module/class.rb => module/class => Module::Class
                    lchomp(filename, "#{app.root.join(load_dir)}/").chomp('.rb').camelize
                  end
                end
              end
            end.flatten.reject { |m| m.starts_with?('Concerns::') }
    

    The advantage being that it loads models in associated engines, not just in your current app.

提交回复
热议问题