2009-09-09 47 views
1

我有一個類,像這樣:創建新類從可選信息屬性不specifiying名稱

class Item 
    attr_accessor :item_id, :name, :address, :description, :facilities, :ratings, :directions, :geo, :images, :video, :availability 

    def self.create options={} 
    item = Item.new 
    item.item_id = options[:item_id] 
    item.name = options[:name] 
    item.description = options[:desc] 
    item.ratings = options[:rating] 
    return item 
    end 

end 

我怎樣才能讓「創造」的方法以這樣的方式來閱讀那些獲得給定的選項通過並嘗試創建它們而不必明確指定它們的名稱?

即。沒有item.name =選項[:item_id]等等等......只是......電腦大腦認爲「啊......我看到選項」選項[:名稱],讓我試着創建一個同名的屬性!並且這個值...」

回答

1
class Item 
    attr_accessor :a, :b, :c 
    def initialize(options = {}) 
    options.each { 
     |k,v| 
     self.send("#{k.to_s}=".intern, v) 
    } 
    end 
end 

i = Item.new(:a => 1, :c => "dog") 
puts i.a 
# outputs: 1 
puts i.c 
# outputs: "dog" 

如果你感覺特別冒險:

class Object 
    def metaclass; class << self; self; end; end 
end 

class Item 
    def initialize(options = {}) 
    options.each { 
     |k,v| 
     self.metaclass.send(:attr_accessor, k) 
     self.send("#{k.to_s}=".intern, v) 
    } 
    end 
end 

i = Item.new(:a => 1, :c => "dog") 
puts i.a 
# 1 
puts i.c 
# dog 

i2 = Item.new 
puts i2.a 
# ERROR 
+0

你是我最好的朋友! – holden 2009-09-09 12:38:31