# Convert string to AR class

**URL:** <https://www.ruby-forum.com/t/convert-string-to-ar-class/76527>\
**Category:** Rails\
**Created:** [March 4, 2006, 4:57am UTC](https://www.ruby-forum.com/t/convert-string-to-ar-class/76527 "2006-03-04T04:57:00Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [March 4, 2006, 4:57am UTC](https://www.ruby-forum.com/t/convert-string-to-ar-class/76527/1 "2006-03-04T04:57:00Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [March 4, 2006, 6:52am UTC](https://www.ruby-forum.com/t/convert-string-to-ar-class/76527/2 "2006-03-04T06:52:28Z")

</div>

“SomeClass”.constantize.find(:all)

–  
Kent

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [March 4, 2006, 8:17am UTC](https://www.ruby-forum.com/t/convert-string-to-ar-class/76527/3 "2006-03-04T08:17:37Z")

</div>

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
