class Class
def attr_accessor_with_history(attr_name)
attr_name = attr_name.to_s
attr_reader attr_name
attr_reader attr_name + "_history"
class_eval %Q{
def #{attr_name}=(new_value)
@#{attr_name}_history = [nil] if @#{attr_name}_history.nil?
@#{attr_name}_history << @#{attr_name} = new_value
end
}
end
end
class Example
attr_accessor_with_history :foo
attr_accessor_with_history :bar
end
有一种Class.attr_accessor_with_history
方法可以提供与该属性相同的功能,attr_accessor
但也可以跟踪该属性曾经拥有的每个值。
> a = Example.new; a.foo = 2; a.foo = "test"; a.foo_history
=> [nil, 2, "test"]
但,
> a = Example.new; a.foo_history
=> nil
它应该是[nil
。
如何为每个
值初始化为的类定义单个initialize
方法?Example
…_history
[nil]