Skip to content

Instantly share code, notes, and snippets.

@ksol
Created October 16, 2015 07:50
Show Gist options
  • Select an option

  • Save ksol/9782e9131e1d779580e1 to your computer and use it in GitHub Desktop.

Select an option

Save ksol/9782e9131e1d779580e1 to your computer and use it in GitHub Desktop.
Example without decorators
class Memoizer
def self.memoize(method_name)
# Getting the method as an object
target_method = instance_method(method_name)
# Overriding it !
define_method(method_name) do |*args, &blk|
# Initializing the cache object
@_memoize_storage ||= {}
if @_memoize_storage[method_name]
# Cached? Do not compute !
puts "Returning cached valued"
else
# Not cached? compute and store the result !
puts "Computing value"
decorated = target_method.bind(self)
@_memoize_storage[method_name] = decorated.call(*args, &blk)
end
# Return the cached result
@_memoize_storage[method_name]
end
end
memoize def run
sleep(3)
1 + 1
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment