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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With