【发布时间】:2012-03-06 03:23:15
【问题描述】:
我试图扩展code from this question 以保存属性值的记录。但是,我的代码在多个属性的情况下会失败。这是代码:
class Class
def attr_accessor_with_history(attr_name)
attr_name = attr_name.to_s
attr_reader attr_name
ah=attr_name+"_history"
attr_reader ah
class_eval %Q{
def #{attr_name}= (attr_name)
@attr_name=attr_name
if @ah == nil
@ah=[nil]
end
@ah.push(attr_name)
end
def #{ah}
@ah
end
def #{attr_name}
@attr_name
end
}
end
end
这里是一个用于测试的虚拟类
class Foo
attr_accessor_with_history :bar
attr_accessor_with_history :bar1
end
f = Foo.new
f.bar = 1
f.bar = 2
f.bar1 = 5
p f.bar_history
p f.bar1_history
由于某种原因,f.bar 和 f.bar1 都返回 5 和 f.bar_history = f.bar1_history = [nil, 1, 2, 5]。知道这是为什么吗?
【问题讨论】:
-
#{attr_name}_history方法的代码在哪里? -
糟糕,我没有复制整个代码
标签: ruby