Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate class from name string in Rails?

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.

like image 866
Vjatseslav Gedrovits Avatar asked Dec 28 '12 13:12

Vjatseslav Gedrovits


1 Answers

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 
like image 144
Eugene Rourke Avatar answered Oct 22 '22 00:10

Eugene Rourke