Skip to content

Instantly share code, notes, and snippets.

Created October 15, 2012 17:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/3893788 to your computer and use it in GitHub Desktop.
Save anonymous/3893788 to your computer and use it in GitHub Desktop.
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 getter
attr_reader attr_name+"_history" # create bar_history getter
class_eval %q{"def #{attr_name} = value
#{attr_name}_history = nil
#{attr_name}_history.push(value)}
end
end
class Foo
#attr_accessor_with_history :bar
attr_reader :bar
attr_writer :bar
end
f = Foo.new
f.bar = 1
f.bar = 2
puts f.bar
Return Output
[nil, 1, 2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment