Getting a list of models in a Rails app


#1

Anyone know an easy way of doing this?


#2

On 2/6/07, David F. removed_email_address@domain.invalid wrote:

Anyone know an easy way of doing this?

def get_models
models = []
Dir.glob( RAILS_ROOT + ‘/app/models/*’ ).each do |f|
models << File.basename( f ).gsub( /^(.+).rb/, ‘\1’)
end
models
end


Greg D.
http://destiney.com/


#3

Greg D. wrote:

On 2/6/07, David F. removed_email_address@domain.invalid wrote:

Anyone know an easy way of doing this?

def get_models
models = []
Dir.glob( RAILS_ROOT + ‘/app/models/*’ ).each do |f|
models << File.basename( f ).gsub( /^(.+).rb/, ‘\1’)
end
models
end


Greg D.
http://destiney.com/

Cheers, I was hoping there would be some in-built rails method to do it,
but this will do for now.

Many thanks,

Dave.


#4

this solution tracks the event of deriving from ActiveRecord::Base. it
has
very limited capabilities but maybe it’s helpful for you

class Class
@@ar_classes = []
alias :old_inherited :inherited
def inherited(cls)
@@ar_classes << cls if cls < ActiveRecord::Base
old_inherited cls
end
def self.ar_classes
@@ar_classes
end
end

derived classes can be dumped with >> Class.ar_classes <<

2007/2/6, David F. removed_email_address@domain.invalid:


#5

On Feb 6, 2:50 pm, David F. removed_email_address@domain.invalid
wrote:

Cheers, I was hoping there would be some in-built rails method to do it,
but this will do for now.

You can use:
ActiveRecord::Base.send :subclasses

Depending on your need, you may want to use the approach of looking
for the files. Rails does not load models until necessary, so unless
all the models have been used, looking for subclasses through any
means will not provide you with all your models.

Dan M.