views:

30

answers:

2

How do I call a class from a string containing that class name inside of it? (I guess I could do case/when but that seems ugly.)

The reason I ask is because I'm using the acts_as_commentable plugin, among others, and these store the commentable_type as a column. I want to be able to call whatever particular commentable class to do a find(commentable_id) on it.

Thanks.

+2  A: 

I think what you want is constantize

Documentation: http://apidock.com/rails/Inflector/constantize

That's an RoR construct. I don't know if there's one for ruby core

Jamie Wong
perfect, that's just what I was looking for.
unsorted
For plain Ruby, you'd use `Module.const_get`. The advantage of `constantize` is that it works even with deeply nested namespaces, so you could do `'Functional::Collections::LazyList'.constantize` and get the class LazyList from the module Collections in the module Functional, whereas with `const_get`, you'd have to do something like `'Functional::Collections::LazyList'.split('::').reduce(Module, :const_get)`.
Chuck
+1  A: 
"Object".constantize # => Object
jtbandes
+1 since it was simultaneous
unsorted