Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails: How do I convert a symbol to a class

Given a symbol in rails, how do I get a Class? So I could call something like:

give_class(:post).find(:all)

or similar.

like image 991
dpb Avatar asked Jan 29 '10 18:01

dpb


1 Answers

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

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

Then use the constantize method:

klass = class_name.constantize

Classy!

like image 111
Matchu Avatar answered Sep 20 '22 03:09

Matchu