I tried to to extend the code from this question for keeping records of an attribute value. However, my code fails in the case of more than one attributes. Here is the code:
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
Here a dummy class for testing
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
For some reason, f.bar
and f.bar1
both return 5
and f.bar_history = f.bar1_history = [nil, 1, 2, 5]
. Any idea why that is?