Skip to content

Instantly share code, notes, and snippets.

@feiskyer
Created March 3, 2012 06:49
Show Gist options
  • Save feiskyer/1964749 to your computer and use it in GitHub Desktop.
Save feiskyer/1964749 to your computer and use it in GitHub Desktop.
Berkeley SaaS class HW1 Part 5: advanced OOP with some metaprogramming
# advanced OOP with some metaprogramming
class Class
def attr_accessor_with_history(attr_name)
attr_name = attr_name.to_s
# getter
attr_reader attr_name
attr_reader attr_name+"_history"
# 为类动态添加方法
class_eval %{
def #{attr_name}=(val)
@#{attr_name} = val
@#{attr_name}_history = [nil] if @#{attr_name}_history.nil?
@#{attr_name}_history.push(val)
end
}
end
end
class Foo
attr_accessor_with_history :bar
end
f = Foo.new
f.bar = 1
f.bar = 2
p f.bar
p f.bar_history # => if your code works, should be [nil,1,2]
@yamishi13
Copy link

thanks for showing me the correct way to do it but could you tell me where did you learn to do it? on the book of the course?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment