How to instantiate class from name string in Rails? How to instantiate class from name string in Rails? ruby-on-rails ruby-on-rails

How to instantiate class from name string in Rails?


klass = Object.const_get "ClassName"

about class methods

class KlassExample    def self.klass_method        puts "Hello World from Class method"    endendklass = Object.const_get "KlassExample"klass.klass_methodirb(main):061:0> klass.klass_methodHello World from Class method


Others may also be looking for an alternative that does not throw an error if it fails to find the class. safe_constantize is just that.

class MyClassend"my_class".classify.safe_constantize.new #  #<MyClass:0x007fec3a96b8a0>"omg_evil".classify.safe_constantize.new #  nil 


You can simply convert a string and initialize a class out of it by:

klass_name = "Module::ClassName"klass_name.constantize

To initialize a new object:

klass_name.constantize.new

I hope this turns out to be helpful.Thanks!