public
Last active

Berkeley SaaS class HW1 Part 5: advanced OOP with some metaprogramming

  • Download Gist
HW1_part5.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
# 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]

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?

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.