2009-09-09 22 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