Skip to content

Instantly share code, notes, and snippets.

@pocke
Created March 6, 2019 08:53
Show Gist options
  • Save pocke/1b0b7c932507645f883a1f9164a83cac to your computer and use it in GitHub Desktop.
Save pocke/1b0b7c932507645f883a1f9164a83cac to your computer and use it in GitHub Desktop.
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