如何从 ruby​​ 中的字符串名称创建类实例?

问题描述:

我有一个类的名称,我想创建该类的一个实例,以便我可以遍历该类架构中存在的每个 rails 属性.

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.

我该怎么做?

  1. 我将名称作为要检查的类的字符串
  2. 我想我需要实例化一个类实例,以便我可以
  3. 遍历它的属性并打印它们.

在 Rails 中,你可以这样做:

In rails you can just do:

clazz = 'ExampleClass'.constantize

纯红宝石:

clazz = Object.const_get('ExampleClass')

带模块:

module Foo
  class Bar
  end
end

你会使用

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