# Getting Object From String?

**URL:** <https://www.ruby-forum.com/t/getting-object-from-string/50294>\
**Category:** Ruby\
**Created:** [December 14, 2005, 11:11pm UTC](https://www.ruby-forum.com/t/getting-object-from-string/50294 "2005-12-14T23:11:34Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![HunterSs\_Lists](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/6bbea6/32.png) [@HunterSs\_Lists](https://www.ruby-forum.com/u/HunterSs_Lists)\
**Post date:** [December 14, 2005, 11:11pm UTC](https://www.ruby-forum.com/t/getting-object-from-string/50294/1 "2005-12-14T23:11:34Z")

</div>

Howdy,

I have a class called ‘NewsItem’.

In one of my Rails classes, I have a place to pass in a string (from a  
HTTP  
parameter). That string’s value is ‘NewsItem’, the class name.

How can I convert that to use as the class?

I.e.

@model = params[:modelname]  
@items = @model.find(:all)

This doesn’t work. I was hoping it would work the same way as:  
@items = NewsItem.find(:all)

How can I pull this off?

Thanks!

---

<div class="post-metadata">

**Author:** ![HunterSs\_Lists](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/6bbea6/32.png) [@HunterSs\_Lists](https://www.ruby-forum.com/u/HunterSs_Lists)\
**Post date:** [December 14, 2005, 11:19pm UTC](https://www.ruby-forum.com/t/getting-object-from-string/50294/2 "2005-12-14T23:19:00Z")

</div>

Hunter’s Lists wrote:

> Howdy,
> 
> I have a class called ‘NewsItem’.
> 
> In one of my Rails classes, I have a place to pass in a string (from a  
> HTTP  
> parameter). That string’s value is ‘NewsItem’, the class name.
> 
> How can I convert that to use as the class?
> 
> I.e.
> 
> @model = params[:modelname]  
> @items = @model.find(:all)
> 
> This doesn’t work. I was hoping it would work the same way as:  
> @items = NewsItem.find(:all)
> 
> How can I pull this off?

# This takes into account nested class names

@model = params[:modelname].split(’::’).inject(Object) {|parent, klass|  
parent.const\_get klass}

> Thanks!

E

---

<div class="post-metadata">

**Author:** ![HunterSs\_Lists](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/6bbea6/32.png) [@HunterSs\_Lists](https://www.ruby-forum.com/u/HunterSs_Lists)\
**Post date:** [December 14, 2005, 11:20pm UTC](https://www.ruby-forum.com/t/getting-object-from-string/50294/3 "2005-12-14T23:20:36Z")

</div>

On Dec 14, 2005, at 4:10 PM, Hunter’s Lists wrote:

> I.e.
> 
> @model = params[:modelname]  
> @items = @model.find(:all)

Try changing the last line to:

@items = Object.const\_get(@model).find(:all)

Hope that helps.

James Edward G. II
