Created
December 14, 2009 23:15
-
-
Save ehrenmurdick/256538 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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