Skip to content

Instantly share code, notes, and snippets.

@richardtifelt
Forked from evan/gist:256524
Created December 14, 2009 23:09
Show Gist options
  • Save richardtifelt/256533 to your computer and use it in GitHub Desktop.
Save richardtifelt/256533 to your computer and use it in GitHub Desktop.
class Class
def memoize(*methods)
methods.each do |method_name|
safe_method_name = method_name.to_s.gsub(/(\!|\?)/, '_')
class_eval("
alias :'#{safe_method_name}_without_memo' :'#{method_name}'
def #{method_name}
if defined?(@#{safe_method_name})
@#{safe_method_name}
else
@#{safe_method_name} = #{safe_method_name}_without_memo
end
end", __FILE__, __LINE__)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment