Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get a list of all models from rails [duplicate]

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

like image 422
gustavgans Avatar asked Aug 05 '09 14:08

gustavgans


3 Answers

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"
  } 
like image 143
Senad Uka Avatar answered Nov 13 '22 04:11

Senad Uka


in rails 3 you'd swap @models for:

@models = ActiveRecord::Base.subclasses.collect { |type| type.name }.sort
like image 22
Jeff Schoolcraft Avatar answered Nov 13 '22 04:11

Jeff Schoolcraft


@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.

like image 8
Amit Thawait Avatar answered Nov 13 '22 02:11

Amit Thawait