20

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']

gustavgans
  • 5,141
  • 13
  • 41
  • 51

5 Answers5

24

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"
  } 
Senad Uka
  • 1,131
  • 7
  • 18
  • 1
    This code works for me, except that I sometimes get warnings when I re-require a model file that was already required earlier. I was able to resolve this by using expand_path, see the bottom of http://devblog.avdi.org/2009/10/22/double-load-guards-in-ruby/ – DSimon Jun 14 '12 at 20:09
  • 2
    A little correction hope you don't mind, RAILS_ROOT has been changed to Rails.root – Rubyrider Apr 30 '13 at 11:25
22

in rails 3 you'd swap @models for:

@models = ActiveRecord::Base.subclasses.collect { |type| type.name }.sort
8
@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.

Amit Thawait
  • 4,862
  • 2
  • 31
  • 25
6

For Rails 3

@models = ActiveRecord::Base.
    descendants.
    select{|x| x.name[-4..-1] == "Cube"}
mike
  • 431
  • 3
  • 8
4

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
equivalent8
  • 13,754
  • 8
  • 81
  • 109