How to instantiate class from name string in Rails?

Vjatseslav Gedrovits picture Vjatseslav Gedrovits · Dec 28, 2012 · Viewed 37.8k times · Source

How we can instantiate class from it's name string in Ruby-on-Rails?

For example we have it's name in database in format like "ClassName" or "my_super_class_name".

How we can create object from it?

Solution:

Was looking for it myself, but not found, so here it is. Ruby-on-Rails API Method

name = "ClassName"
instance = name.constantize.new  

It can be even not formatted, we can user string method .classify

name = "my_super_class"
instance = name.classify.constantize.new

Of course maybe this is not very 'Rails way', but it solves it's purpose.

Answer

Eugene Rourke picture Eugene Rourke · Dec 28, 2012
klass = Object.const_get "ClassName"

about class methods

class KlassExample
    def self.klass_method
        puts "Hello World from Class method"
    end
end
klass = Object.const_get "KlassExample"
klass.klass_method

irb(main):061:0> klass.klass_method
Hello World from Class method