views:

194

answers:

2

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

give_class(:post).find(:all)

or similar.

+3  A: 

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!

Matchu
Edit that answer to include camelize/classify bit, and I'll accept it!
dpb
Seems odd, but sure.
Matchu
Edits made. Tah dah!
Matchu
tah dah back! :)
dpb
+2  A: 

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:

  • .to_s.camelize - used when you have the singular form (:post)
  • .to_s.classify - used when you have a plural form (:posts)

From that, you call constantize, and Viola! you have your class.

dpb
Mhm. It depends on if you are going to be passing in the actual class name `:MyClass`, or prefer the `:my_class` format.
Matchu
Yeah, that is right. That was the part that was tripping me up. Especially the difference between singular and plural.
dpb