Converting table names to model names

Hi,

I’m trying to get a list of all models in my app without looking at
the /models folder on disk (long story).

I thought I’d just get the table names and convert them into class
names:

ActiveRecord::Base.connection.tables.map { |t| t.classify }

But there are a couple of exceptions, like schema_info and
schema_migrations. So I thought I’d check to see if the resulting
classifcation actually exists as a class, but I can only think of an
ugly way to check:

eval t.classify rescue nil # throws an exception if the class does
not exist

Is there any way I can avoid the ugly eval?

Thanks!
Jeff

I remember vaguely that ActiveRecord keeps track of
all the models derived from it.
It had some protected method to get them all which you
could access with the send method.

Have a look in the ActiveRecord sources to get more details.

Another way to do it is that there is a ruby method called
const_defined? or something like that, you can google for it, and you
can check to see if the class name is defined.

Jamey

ActiveRecord::Base.send(:subclasses)

And then you probably want to avoid some (like
CGI::Session::ActiveRecordStore::Session)

I use this in:
def self.posers
[CGI::Session::ActiveRecordStore::Session]
end

 for klass in ActiveRecord::Base.send(:subclasses)
   next if posers.include?(klass)

Hope that helps.

-Rob

On Jul 11, 2008, at 12:22 PM, Jeff wrote:

Thanks!
Jeff

Rob B. http://agileconsultingllc.com
[email protected]
+1 513-295-4739
Skype: rob.biedenharn