Module: Lemo::Memo::ClassMethods
- Defined in:
- lib/lemo/memo.rb
Instance Method Summary collapse
-
#ivar_from(maybe_meth) ⇒ Object
provide a legal ivar name from a method name.
- #lemo(meth) ⇒ Object (also: #memo)
- #memoed_methods ⇒ Object
Instance Method Details
#ivar_from(maybe_meth) ⇒ Object
provide a legal ivar name from a method name. instance variables can’t have ? ! and other punctuation. Which isn’t handled. Obviously.
16 17 18 |
# File 'lib/lemo/memo.rb', line 16 def ivar_from( maybe_meth ) :"@_memo_#{maybe_meth.to_s.tr ILLEGAL_IVAR_CHARS,'pi'}" end |
#lemo(meth) ⇒ Object Also known as: memo
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/lemo/memo.rb', line 20 def lemo( meth ) unbound_previous_method = instance_method meth # still doesn't prevent memoisation of methods with an implicit block unless unbound_previous_method.parameters.empty? raise ArgumentError, "can't memo #{meth} with parameters" end memoed_methods[meth] = unbound_previous_method ivar = ivar_from meth define_method meth do # This gets executed on every call to meth, so make it fast. if instance_variable_defined? ivar instance_variable_get ivar else # bind the saved method to this instance, call the result ... to_memo = unbound_previous_method.bind( self ).call # ... memo it and return value instance_variable_set ivar, to_memo end end meth end |
#memoed_methods ⇒ Object
10 11 12 |
# File 'lib/lemo/memo.rb', line 10 def memoed_methods @memoed_methods ||= {} end |