How do I create a class instance from a string name in ruby?

后端 未结 4 1961
既然无缘
既然无缘 2020-11-29 18:55

I have the name of a class and I want to create an instance of that class so that I can loop through each rails attribute that is present in the schema of that class.

<
4条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 19:16

    Very simple in Rails: use String#constantize

    class_name = "MyClass"
    instance = class_name.constantize.new
    

提交回复
热议问题