Given a symbol in rails, how do I get a Class? So I could call something like:
give_class(:post).find(:all)
or similar.
Given a symbol in rails, how do I get a Class? So I could call something like:
give_class(:post).find(:all)
or similar.
First, convert to string.
class_name = symbol.to_s
From there, you will need to format the string into a proper class name using the methods provided by ActiveSupport's Inflections module.
camelize will turn 'my_module' into 'MyModule'classify will turn 'my_models' into 'MyModel'camelize is more likely the one you want, given your code snippet.
The use the constantize method:
klass = class_name.constantize
Classy!
I was searching stackoverflow for this answer and couldn't find it worded how I was looking for it, so I thought I would Q&A myself:
The answer above was correct, but I acutally found the docs that explain a bit better:
There are basically two methods:
From that, you call constantize, and Viola! you have your class.