Skip to content

Instantly share code, notes, and snippets.

@gregwebs
Created October 8, 2010 19:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gregwebs/617363 to your computer and use it in GitHub Desktop.
Save gregwebs/617363 to your computer and use it in GitHub Desktop.
def self.cached_method(meth)
eval <<-CODE
def #{meth}_with_cache
return @#{meth} if @#{meth}
result = #{meth}_without_cache
@#{meth} ||= result
end
CODE
alias_method_chain meth, :cache
end
def self.memoized_method(meth)
eval <<-CODE
def #{meth}_with_memoization(*args)
@#{meth}_with_memoization ||= {}
@#{meth}_with_memoization[args] ||= #{meth}_without_memoization(*args)
end
CODE
alias_method_chain meth, :memoization
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment