Forum: Ruby on Rails convert string to AR class

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
8adbed24cb8d91bfb8dce6cf1e7141b6?d=identicon&s=25 Mat (Guest)
on 2006-03-04 04:57
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
3ccecc71b9fb0a3d7f00a0bef6f0a63a?d=identicon&s=25 Kent Sibilev (Guest)
on 2006-03-04 06:52
(Received via mailing list)
"SomeClass".constantize.find(:all)

--
Kent
8adbed24cb8d91bfb8dce6cf1e7141b6?d=identicon&s=25 Mat (Guest)
on 2006-03-04 08:17
Kent Sibilev 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
This topic is locked and can not be replied to.