Skip to content

Instantly share code, notes, and snippets.

@ehrenmurdick
Created December 14, 2009 23:15
Show Gist options
  • Save ehrenmurdick/256538 to your computer and use it in GitHub Desktop.
Save ehrenmurdick/256538 to your computer and use it in GitHub Desktop.
require 'activesupport'
class Module
def memoize method
define_method :"#{method}_with_memoization" do |*args|
varname = "@_memoized_#{method}"
if instance_variable_names.include?(varname)
instance_variable_get(varname)
else
instance_variable_set(varname, send("#{method}_without_memoization"))
end
end
alias_method_chain method, :memoization
end
end
class Foo
def bar
rand(1000)
end
memoize :bar
end
f = Foo.new
p [f.bar, f.bar]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment