Skip to content

Instantly share code, notes, and snippets.

@dchelimsky
Created September 18, 2009 22:12
Show Gist options
  • Save dchelimsky/189324 to your computer and use it in GitHub Desktop.
Save dchelimsky/189324 to your computer and use it in GitHub Desktop.
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