Skip to content

Instantly share code, notes, and snippets.

@sriedel
Created February 20, 2020 06:20
Show Gist options
  • Save sriedel/9610b949f7514fac7d13327f934ce383 to your computer and use it in GitHub Desktop.
Save sriedel/9610b949f7514fac7d13327f934ce383 to your computer and use it in GitHub Desktop.
module Memoize
def memoize(method_name)
ivar_name = :"@#{method_name}"
aliased_method_name = :"__unmemoized_#{method_name}"
alias_method aliased_method_name, method_name
define_method method_name do
return instance_variable_get(ivar_name) if instance_variable_defined?(ivar_name)
instance_variable_set(ivar_name, send(aliased_method_name))
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment