Bula Bula - 1 year ago 66
Ruby Question

Make Rails recognise my class inside a string

I have a variable that stores the name of a class

my_class = "Homework"

This class has certain attributes which I would like to access


How can I make ruby see this string as an object?



Answer Source

You can use classify and constantize

my_class.classify.constantize.find_by # something


Create a class name from a plural table name like Rails does for table names to models. Note that this returns a string and not a Class (To convert to an actual class follow classify with constantize).


Tries to find a constant with the name specified in the argument string.

'Module'.constantize     # => Module 
'Test::Unit'.constantize # => Test::Unit

If you are sure about your input, you need only constantize

my_class.constantize.find_by # something
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download