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

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

    module One
      module Two
        class Three
          def say_hi
            puts "say hi"
          end
        end
      end
    end
    
    one = Object.const_get "One"
    
    puts one.class # => Module
    
    three = One::Two.const_get "Three"
    
    puts three.class # => Class
    
    three.new.say_hi # => "say hi"
    

    In ruby 2.0 and, possibly earlier releases, Object.const_get will recursively perform a lookup on a namespaces like Foo::Bar. The example above is when the namespace is known ahead of time and highlights the fact that const_get can be called on modules directly as opposed to exclusively on Object.

提交回复
热议问题