【问题标题】:Creating a Ruby Class on the fly without eval在没有 eval 的情况下即时创建 Ruby 类
【发布时间】:2012-06-11 12:46:20
【问题描述】:

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

eval %Q{
  class ::#{klass} < ActiveRecord::Base
    self.table_name = "#{table_name}"
  end
}

在不使用eval 的情况下,是否有等效且至少同样简洁的方法?

【问题讨论】:

    标签: ruby metaprogramming eval


    【解决方案1】:

    您可以使用Class 类,其中类是实例。迷茫了吗? ;)

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

    【讨论】:

    • 就是这样,谢谢。我知道类也是对象;但我不知道可以将基类作为参数,特别是关于块(事后看来,我应该猜到了)。
    【解决方案2】:

    当然有:)

    class Foo
      class << self
        attr_accessor :table_name
      end
    end
    
    Bar = Class.new(Foo) do
      self.table_name = 'bars'
    end
    
    Bar.table_name # => "bars"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-02
      • 2012-03-27
      • 2015-07-07
      • 1970-01-01
      • 2012-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多