3

我有这堂课:

class PriceChange
  attr_accessor :distributor_id, :product_id, :value, :price_changed_at, :realm

  def initialize(data = {})
    @distributor_id   = data[:distributor_id]
    @product_id       = data[:product_id]
    @value            = data[:value]
    @price_changed_at = data[:price_changed_at]
    @realm            = data[:realm]
  end
end

而且我想避免方法体内的映射。我想要一种透明而优雅的方式来设置实例属性值。我知道我可以遍历数据键并使用类似define_method. 我不想要这个。我想以一种干净的方式做到这一点。

4

1 回答 1

4

我想以一种干净的方式做到这一点。

如果不定义它们,您将不会获得attr_accessors 和实例变量。下面是使用一些简单的元编程(它是否符合“干净”的条件?)

class PriceChange
  def initialize(data = {})
    data.each_pair do |key, value|
      instance_variable_set("@#{key}", value)
      self.class.instance_eval { attr_accessor key.to_sym }
    end
  end
end

用法:

price_change = PriceChange.new(foo: :foo, bar: :bar)
#=> #<PriceChange:0x007fb3a1755178 @bar=:bar, @foo=:foo>
price_change.foo
#=> :foo
price_change.foo = :baz
#=> :baz
price_change.foo
#=> :baz
于 2017-04-04T15:39:46.137 回答