Home How to instantiate class from string in Rails?
Post
Cancel

How to instantiate class from string in Rails?

How to instantiate class from string in Rails?

1
result_object = Object.const_get "ClassName"

Below is an example how to instantiate class and call methods

1
2
3
4
5
6
# ukraine.rb
class Ukraine
  def say
    puts "Stop Putin! Stop War in Ukraine!!!"
  end
end
1
2
3
4
# Terminal: Development
irb(main):001:0> ukraine = Object.const_get "Ukraine"
irb(main):001:0> ukraine.say
--> Stop Putin! Stop War in Ukraine!!!
This post is licensed under CC BY 4.0 by the author.