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

后端 未结 4 1964
既然无缘
既然无缘 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:18

    In rails you can just do:

    clazz = 'ExampleClass'.constantize
    

    In pure ruby:

    clazz = Object.const_get('ExampleClass')
    

    with modules:

    module Foo
      class Bar
      end
    end
    

    you would use

    > clazz = 'Foo::Bar'.split('::').inject(Object) {|o,c| o.const_get c}
      => Foo::Bar 
    > clazz.new
      => # 
    

提交回复
热议问题