在没有eval的情况下动态创建Ruby类

DrT*_*Tom 5 ruby eval metaprogramming

我需要动态创建一个Ruby类,即动态的,派生自ActiveRecord::Base.我eval暂时使用:

eval %Q{
  class ::#{klass} < ActiveRecord::Base
    self.table_name = "#{table_name}"
  end
}
Run Code Online (Sandbox Code Playgroud)

是否有一种等效的,至少同样简洁的方法来做到这一点而不使用eval

d11*_*wtq 14

您可以使用Class类,其中的类是实例.困惑了吗?;)

cls = Class.new(ActiveRecord::Base) do
  self.table_name = table_name
end

cls.new
Run Code Online (Sandbox Code Playgroud)


Ser*_*sev 4

当然有:)

class Foo
  class << self
    attr_accessor :table_name
  end
end

Bar = Class.new(Foo) do
  self.table_name = 'bars'
end

Bar.table_name # => "bars"
Run Code Online (Sandbox Code Playgroud)