Created
March 3, 2012 06:49
-
-
Save feiskyer/1964749 to your computer and use it in GitHub Desktop.
Berkeley SaaS class HW1 Part 5: advanced OOP with some metaprogramming
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?