Skip to content

Instantly share code, notes, and snippets.

@teamon
Last active August 29, 2015 14:01
Show Gist options
  • Save teamon/21d52223fb7a27e471e7 to your computer and use it in GitHub Desktop.
Save teamon/21d52223fb7a27e471e7 to your computer and use it in GitHub Desktop.
module CachedDef
def cached(name)
meth = instance_method(name)
raise ArgumentError.new("cached can be used only for method with no arguments") if meth.arity != 0
alias_method "__cached_def_original__#{name}", name
class_eval <<-EOS
def #{name}
@__cached_def_cache__#{name} ||= __cached_def_original__#{name}
end
EOS
end
end
class Foo
extend CachedDef
def bar
puts "computing bar"
sleep 0.5
1
end
cached def cached_bar
puts "computing cached_bar"
sleep 0.5
2
end
end
foo = Foo.new
3.times { puts foo.bar }
3.times { puts foo.cached_bar }
⌘ ~/scratch λ ruby cached_def.rb
computing bar
1
computing bar
1
computing bar
1
computing cached_bar
2
2
2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment