Created
March 6, 2019 08:53
-
-
Save pocke/1b0b7c932507645f883a1f9164a83cac 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 Cacheable | |
def cache(method_name) | |
orig_name = :"__orig__#{method_name}" | |
alias_method orig_name, method_name | |
define_method method_name do | |
__send__(orig_name).tap do |res| | |
self.class.class_eval do | |
undef_method method_name | |
undef_method orig_name | |
define_method method_name do | |
res | |
end | |
end | |
end | |
end | |
end | |
end | |
class A | |
extend Cacheable | |
cache def foo | |
sleep 1 | |
:foo | |
end | |
end | |
a = A.new | |
p a.foo | |
p a.foo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment