[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Getting Object From String?

Hunter's Lists

12/14/2005 10:11:00 PM

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!




2 Answers

Eero Saynatkari

12/14/2005 10:19:00 PM

0

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

--
Posted via http://www.ruby-....


James Gray

12/14/2005 10:19:00 PM

0

On Dec 14, 2005, at 4:10 PM, 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)

Try changing the last line to:

@items = Object.const_get(@model).find(:all)

Hope that helps.

James Edward Gray II