2017-04-04 79 views
1

我有這個類:轉換哈希PARAMS到實例變量上的Ruby初始化

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的東西。我不想要這個。 我想以一種乾淨的方式做到這一點。

回答

1

我想以乾淨的方式做到這一點。

您不會得到attr_accessor s和實例變量而不定義它們。下面是使用一些簡單的元編程(是否有資格獲得「乾淨」?)

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 
+0

您的代碼無疑是非常乾淨的,但正如我說:「我知道我可以遍歷數據鍵並使用類似define_method的東西「。我正在尋找一種「透明」的方式。也許不存在。 – Leantraxxx

+1

@Leantraxxx它不存在,AFAICT –