[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

get class instance from name?

Kevin McConnell

4/26/2005

What's a good way to get at a Class instance, from a string containing
its name?

For example, say I have a string "Customer", and want to call
Customer.my_class_method(). I realise I could do something like:

# class_name = "Customer"
result = eval("#{class_name}.my_class_method()")

....but it smells like a hack to me, and so I suspect there's a more
"proper" way to get at the object I need...

Any pointers would be much appreciated!

Cheers,
Kevin
2 Answers

James Gray

4/26/2005 12:10:00 AM

0

On Apr 25, 2005, at 7:04 PM, Kevin McConnell wrote:

> What's a good way to get at a Class instance, from a string containing
> its name?
>
> For example, say I have a string "Customer", and want to call
> Customer.my_class_method(). I realise I could do something like:
>
> # class_name = "Customer"
> result = eval("#{class_name}.my_class_method()")
>
> ....but it smells like a hack to me, and so I suspect there's a more
> "proper" way to get at the object I need...
>
> Any pointers would be much appreciated!

You're looking for Module.const_get(). Use it to get the class object,
then call the method.

Hope that helps.

James Edward Gray II



Kevin McConnell

4/26/2005 2:10:00 AM

0

James Edward Gray II wrote:

> You're looking for Module.const_get(). Use it to get the class object,
> then call the method.

Yep, that's exactly what I needed.

Thanks!