There seem to be a mistake in my code. However I just can’t find it out.
class Class
def attr_accessor_with_history(attr_name)
attr_name = attr_name.to_s
attr_reader attr_name
attr_writer attr_name
attr_reader attr_name + "_history"
class_eval %Q{
@#{attr_name}_history=[1,2,3]
}
end
end
class Foo
attr_accessor_with_history :bar
end
f = Foo.new
f.bar = 1
f.bar = 2
puts f.bar_history.to_s
I would expect it to return an array [1,2,3]. However, it doesn’t return anything.
You will find a solution for your problem in Sergios answer. Here an explanation, what’s going wrong in your code.
With
you execute
You execute this on class level, not in object level.
The variable
@bar_historyis not available in a Foo-object, but in the Foo-class.With
you access the -never on object level defined- attribute @bar_history.
When you define a reader on class level, you have access to your variable: