Convert string to AR class


#1

Hi everyone,

I’m trying to convert a string passed on the command-line into an
ActiveRecord class, so I can do something like this.

a="SomeClass"
a.find(:all)

where

class SomeClass < ActiveRecord::Base
end

This appears to work (better ways would be appreciated):

a="SomeClass"
b=eval a
b.find(:all)

However I would like to make sure this is an real class first, so I
tried this since class names are constants:

a="SomeClass"
Modules.constants.include?( a )

but SomeClass will not show up if it has not been used yet. So I
switched to

a="SomeClass"
begin
  b=eval a
  b.class # for at least one use
rescue
  puts "error"; exit
end

Now I want to find out if it is derived from ActiveRecord, but can’t
seem to figure out how. I looked at Modules#ancestors and
Module#nesting, but this does not seem to be the right thing. Any help
would be greatly appreciated.

Thanks,
Mat Cucuzella


#2

“SomeClass”.constantize.find(:all)


Kent


#3

Kent S. wrote:

“SomeClass”.constantize.find(:all)

That’s it! And after the following code does correctly check for derived
from AR

a="SomeClass".constantize
a.ancestors.include? ActiveRecord::Base

Thanks for your help.
Mat Cucuzella