List of all Models


#1

Anyone know a pretty way to get a list of all Models?

That is, a list of all classes which inherit from ActiveRecord:Base

I can’t seem to figure it out!

The best I’ve got is to list the /app/models directory… but, that is
dirty.

-hampton.


#2

On 4/7/06, Hampton removed_email_address@domain.invalid wrote:

Anyone know a pretty way to get a list of all Models?

That is, a list of all classes which inherit from ActiveRecord:Base

I can’t seem to figure it out!

The best I’ve got is to list the /app/models directory… but, that is
dirty.

You can do this, but it will only show all of your models once they
have been loaded. If nothing has 'require’d them yet, they won’t show
up.

found = []
ObjectSpace.each_object(Class) do |klass|
found << klass if klass.ancestors.include?(ActiveRecord::Base)
end

[ActiveRecord::Base, CGI::Session::ActiveRecordStore::Session,
SomeModel, SomeOtherModel]

A shortcut (which I don’t recommend) is to call:
ActiveRecord::Base.send(:subclasses)

…which is probably a bad idea, because it invokes a private method on
ActiveRecord::Base.


#3

Anyone know a pretty way to get a list of all Models?

Not tested but something like the code below …

def list_all_models
ObjectSpace.each_object(Class) do |klass|
return klass.select {|k| k.kind_of?(ActiveRecord::Base)}
end
end

Steven Beales

“Wilson B.” removed_email_address@domain.invalid wrote
in message
news:removed_email_address@domain.invalid…
On 4/7/06, Hampton removed_email_address@domain.invalid wrote:

Anyone know a pretty way to get a list of all Models?

That is, a list of all classes which inherit from ActiveRecord:Base

I can’t seem to figure it out!

The best I’ve got is to list the /app/models directory… but, that is
dirty.

You can do this, but it will only show all of your models once they
have been loaded. If nothing has 'require’d them yet, they won’t show
up.

found = []
ObjectSpace.each_object(Class) do |klass|
found << klass if klass.ancestors.include?(ActiveRecord::Base)
end

[ActiveRecord::Base, CGI::Session::ActiveRecordStore::Session,
SomeModel, SomeOtherModel]

A shortcut (which I don’t recommend) is to call:
ActiveRecord::Base.send(:subclasses)

…which is probably a bad idea, because it invokes a private method on
ActiveRecord::Base.


#4

You’ve got to make sure all the models have been loaded first. This
should
work:

Dir.glob(RAILS_ROOT + ‘/app/models/*.rb’).each { |file| require file }
models = Object.subclasses_of(ActiveRecord::Base)

-Jonathan.