I need a list with all models (class_names) which have the pattern "Cube" at the end.
example:
all my models: ModelFoo, ModelBar, ModelBarCube, Mode2BarCube
what I need:
['ModelBarCube', 'Mode2BarCube']
I need a list with all models (class_names) which have the pattern "Cube" at the end.
example:
all my models: ModelFoo, ModelBar, ModelBarCube, Mode2BarCube
what I need:
['ModelBarCube', 'Mode2BarCube']
Since Rails doesn't load classes unless it needs them, you must read the models from the folder. Here is the code
Dir.glob(Rails.root + '/app/models/*.rb').each { |file| require file }
@models = Object.subclasses_of(ActiveRecord::Base).select { |model|
model.name[-4..-1] == "Cube"
}
in rails 3 you'd swap @models for:
@models = ActiveRecord::Base.subclasses.collect { |type| type.name }.sort
@models = ActiveRecord::Base.descendants.map(&:name)
gives you all the model names which either inherit form ActiveRecord::Base
or is a subclass of any existing model.
For Rails 3
@models = ActiveRecord::Base.
descendants.
select{|x| x.name[-4..-1] == "Cube"}
I was googling answer how to show all Ralis models, combination of answers here was weary helpful, thx.
so here is combination of solutions that works even for STI tables on Rails
#Since Rails doesn't load classes unless it needs them, you must read the models from the folder. Here is the code
Dir[Rails.root.to_s + '/app/models/**/*.rb'].each do |file|
begin
require file
rescue
end
end
models = ActiveRecord::Base.subclasses.collect { |type| type.name }.sort
models.each do |model|
print model
print ' '
end