Is there a way that you can get a collection of all of the Models in your Rails app?
Basically, can I do the likes of: -
Models.each do |model|
puts model.class.name
end
Is there a way that you can get a collection of all of the Models in your Rails app?
Basically, can I do the likes of: -
Models.each do |model|
puts model.class.name
end
The
Rails
implements the methoddescendants
, but models not necessarily ever inherits fromActiveRecord::Base
, for example, the class that includes the moduleActiveModel::Model
will have the same behavior as a model, just doesn't will be linked to a table.So complementing what says the colleagues above, the slightest effort would do this:
Monkey Patch of class
Class
of the Ruby:and the method
models
, including ancestors, as this:The method
Module.constants
returns (superficially) a collection ofsymbols
, instead of constants, so, the methodArray#select
can be substituted like this monkey patch of theModule
:Monkey patch of
String
.And, finally, the models method
Here's a solution that has been vetted with a complex Rails app (the one powering Square)
It takes the best parts of the answers in this thread and combines them in the simplest and most thorough solution. This handle cases where your models are in subdirectories, use set_table_name etc.
EDIT: Look at the comments and other answers. There are smarter answers than this one! Or try to improve this one as community wiki.
Models do not register themselves to a master object, so no, Rails does not have the list of models.
But you could still look in the content of the models directory of your application...
EDIT: Another (wild) idea would be to use Ruby reflection to search for every classes that extends ActiveRecord::Base. Don't know how you can list all the classes though...
EDIT: Just for fun, I found a way to list all classes
EDIT: Finally succeeded in listing all models without looking at directories
If you want to handle derived class too, then you will need to test the whole superclass chain. I did it by adding a method to the Class class:
This will give to you all the model classes you have on your project.
Just came across this one, as I need to print all models with their attributes(built on @Aditya Sanghi's comment):
On one line:
Dir['app/models/\*.rb'].map {|f| File.basename(f, '.*').camelize.constantize }