views:

64

answers:

1

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|  
  associations = model.reflect_on_all_associations(:has_many)  
  ... do some stuff  
end

My question is how do I inspect my rails app to get a collection of the models (rails_env.models) ?

A: 

Iterate over all files in `$RAILS_ROOT\app\models' ?

For instance

def find_all_models
  # iterate over all files in folder
  folder = File.join(RAILS_ROOT, "app", "models")      
  Dir[File.join(folder, "*")].each do |filename|
    # remove .rb
    model_name = File.basename(filename).sub(/.rb$/, '').capitalize
    model = Kernel.const_get(model_name)
    # .. do something with your model :)
  end
end

Does this help?

nathanvda