Skip to content

Instantly share code, notes, and snippets.

@samleb
Created May 28, 2009 10:48
Show Gist options
  • Save samleb/119220 to your computer and use it in GitHub Desktop.
Save samleb/119220 to your computer and use it in GitHub Desktop.
module Memoized
def method_added(method_name)
if instance_method(method_name).arity.zero?
protecting_against_infinite_method_added_loop do
memoize(method_name)
end
end
end
def memoize(method_name)
sanitized_name = method_name.to_s
sanitized_name = sanitized_name.sub(/!$/, '_bang')
sanitized_name = sanitized_name.sub(/\?$/, '_question')
complete_name = "#{sanitized_name}_#{object_id}"
class_eval(<<-EVAL, __FILE__, __LINE__)
alias compute_#{complete_name} #{method_name} # alias compute_superklass_question_12099690 superklass?
#
def #{method_name} # def superklass?
unless defined?(@#{complete_name}) # unless defined?(@superklass_question_12099690)
@#{complete_name} = compute_#{complete_name} # @superklass_question_12099690 = compute_superklass_question_12099690
end # end
@#{complete_name} # @superklass_question_12099690
end # end
EVAL
end
def protecting_against_infinite_method_added_loop
unless @memoizing
@memoizing = true
yield
@memoizing = false
end
end
end
class Base < Treetop::Runtime::SyntaxNode
extend Memoized
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment