get class instance from name?

K

Kevin McConnell

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
 
J

James Edward Gray II

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
 
K

Kevin McConnell

James said:
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!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top