class Class
def attr_accessor_with_history(attr_name)
attr_name = attr_name.to_s
# make sure it's a string
attr_reader attr_name
# create the attribute's
attr_reader attr_name+"_history" # create bar_history
class_eval %Q{
def #{attr_name}=(val)
@#{attr_name+"_history"}=[]
@#{attr_name+"_history"}.push(val)
@#{attr_name}=val
end
}
end
end
class Foo
attr_accessor_with_history :bar
end
我想创建attr访问器,它会记录数组中所有写入的历史记录,但问题是在class_eval中每次都初始化数组,因此它不会保留旧值。
我应该做些什么改变?