Forum: Ruby on Rails Getting a list of models in a Rails app...

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
David F. (Guest)
on 2007-02-06 21:33
Anyone know an easy way of doing this?
Greg D. (Guest)
on 2007-02-06 21:43
(Received via mailing list)
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/
David F. (Guest)
on 2007-02-06 21:50
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.
Peter E. (Guest)
on 2007-02-06 22:03
(Received via mailing list)
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>:
Dan M. (Guest)
on 2007-02-06 22:21
(Received via mailing list)
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.
This topic is locked and can not be replied to.