Converting table names to model names


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: { |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?


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.



And then you probably want to avoid some (like

I use this in:
def self.posers

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

Hope that helps.


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


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