How to instantiate a class from a name string in Rails?

How can we instantiate a class from its name string in Ruby-on-Rails?

For example, we have this name in the database in the format "ClassName" or "my_super_class_name".

How can we create an object from it?

Decision:

I searched for it myself, but did not find it, so here it is. Ruby-on-Rails API

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

It may not even be formatted, we can use the custom line method .classify

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

Of course, perhaps this is not a very β€œRails path”, but it solves its purpose.

+55
string instantiation class ruby-on-rails ruby-on-rails-3
Dec 28
source share
4 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 
+56
Dec 28 '12 at 13:41
source share

Others may also look for an alternative that does not throw an error if they cannot find the class. safe_constantize is easy.

 class MyClass end "my_class".classify.safe_constantize.new # #<MyClass:0x007fec3a96b8a0> "omg_evil".classify.safe_constantize.new # nil 
+23
Mar 06 '15 at 23:53
source share

I am surprised that no one considers security and hacking in their answers. Ignoring an arbitrary string, which most likely indirectly comes from user input, causes problems and hacking. We all should / should be whitelisting if we are not sure that the string is fully controlled and controlled

 def class_for(name) { "foo" => Foo, "bar" => Bar, }[name] || raise UnknownClass end class_for(name_wherever_this_came_from).create!(params_somehow) 

How would you know the appropriate parameters arbitrarily, without having a white list, it would be difficult, but you understood the idea.

+2
Nov 18 '16 at 16:25
source share

You can simply convert the string and initialize the class from it:

 klass_name = "Module::ClassName" klass_name.constantize 

To initialize a new object:

 klass_name.constantize.new 

Hope this is helpful. Thank!

0
Feb 23 '17 at 11:11
source share



All Articles