Last active
August 29, 2015 14:01
-
-
Save teamon/21d52223fb7a27e471e7 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 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 } |
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
⌘ ~/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