Forum: Ruby Getting Object From String?

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.
A7db9ec803b5895ae5f916a74e2db329?d=identicon&s=25 Hunter's Lists (Guest)
on 2005-12-14 23:11
(Received via mailing list)
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!
Fe9b2d0628c0943af374b2fe5b320a82?d=identicon&s=25 Eero Saynatkari (rue)
on 2005-12-14 23:19
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
4299e35bacef054df40583da2d51edea?d=identicon&s=25 James Gray (bbazzarrakk)
on 2005-12-14 23:20
(Received via mailing list)
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 Gray II
This topic is locked and can not be replied to.