Bula Bula - 2 months ago 10
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

Homework.find_by


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

e.g.

my_class.find_by

Answer

You can use classify and constantize

my_class.classify.constantize.find_by # something

classify

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).

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