Created
September 18, 2009 22:12
-
-
Save dchelimsky/189324 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
module ResultCaching | |
def with_result_caching | |
begin | |
@methods_to_cache = [] | |
@caching = true | |
yield | |
@caching = false | |
@methods_to_cache.each do |name| | |
alias_method "cached_#{name}", name | |
class_eval <<-EOF | |
def #{name} | |
@#{name} ||= send :cached_#{name} | |
end | |
EOF | |
end | |
ensure | |
@methods_to_cache = nil | |
@caching = false | |
end | |
end | |
def method_added(name) | |
if @caching | |
@methods_to_cache << name | |
end | |
super | |
end | |
end | |
class Foo | |
extend ResultCaching | |
with_result_caching do | |
def bar | |
@count ||= 0 | |
@count += 1 | |
end | |
end | |
end | |
foo = Foo.new | |
puts foo.bar | |
puts foo.bar |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment