Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > Getting Object From String?

Reply
Thread Tools

Getting Object From String?

 
 
Hunter's Lists
Guest
Posts: n/a
 
      12-14-2005
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!




 
Reply With Quote
 
 
 
 
Eero Saynatkari
Guest
Posts: n/a
 
      12-14-2005
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-forum.com/.


 
Reply With Quote
 
 
 
 
James Edward Gray II
Guest
Posts: n/a
 
      12-14-2005
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


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: You Mean I Won't Be GEtting Paid More for Getting This Cert? FrisbeeŽ MCSE 0 10-22-2007 03:32 PM
Getting User Input after getting Input from a file dei3cmix@uga.edu C++ 3 03-23-2006 05:01 AM
How to avoid getting BGP routes while getting a router's routing table ncosta@net.ipl.pt Cisco 2 01-25-2006 11:50 AM
Object creation - Do we really need to create a parent for a derieved object - can't the base object just point to an already created base object jon wayne C++ 9 09-22-2005 02:06 AM
Getting name of object instance from within object method Martin Javascript 6 08-20-2004 12:24 PM



Advertisments