List of all Models

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.

On 4/7/06, Hampton [email protected] 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.

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.” [email protected] wrote
in message
news:[email protected]
On 4/7/06, Hampton [email protected] 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.

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.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs