Skip to content

Instantly share code, notes, and snippets.

@rringler
Created April 23, 2017 21:46
Show Gist options
  • Save rringler/a8ea8929853d9fe616e0564e6cc643b7 to your computer and use it in GitHub Desktop.
Save rringler/a8ea8929853d9fe616e0564e6cc643b7 to your computer and use it in GitHub Desktop.
Simple module for memoizing Ruby methods
module Memoizable
# Usage:
#
# class Foo
# extend Memoizable
#
# memoize def bar
# 'bar'
# end
# end
def memoize(method_name)
if interceptor.instance_variable_defined?(:"@memoized_#{method_name}")
raise "The method :#{method_name} has already been memoized."
end
interceptor.send(:define_method, method_name) do |*args, &block|
if instance_variable_defined?(:"@memoized_#{method_name}")
return instance_variable_get(:"@memoized_#{method_name}")
end
instance_variable_set(:"@memoized_#{method_name}", super(*args, &block))
end
end
private
def interceptor
existing_interceptor || create_interceptor
end
def interceptor_name
'MemoizeInterceptor'
end
def existing_interceptor
const_get(interceptor_name) if const_defined?(interceptor_name)
end
def create_interceptor
prepend(const_set(interceptor_name, Module.new))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment