Class: Module

Inherits:
Object show all
Defined in:
lib/lab419/core/memoization.rb

Instance Method Summary collapse

Instance Method Details

#memoize(*method_symbols) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/lab419/core/memoization.rb', line 3

def memoize *method_symbols
  method_symbols.each do | method_symbol |
    mthd = instance_method method_symbol
    remove_method method_symbol
    # The following two variables are the indicators it rests
    # to be seen if including blocks into the memoization is
    # indeed a good idea!
    already_called = {}
    results        = {}
    define_method method_symbol do |*args, &blk|
      ac = already_called[[args,blk]]
#        p called_with: [args,blk], ac?: ac
      return results[[args,blk]] if already_called[[args,blk]]

      already_called[[args,blk]] = true
#        p set_ac: already_called[[args,blk]], for: [args,blk]
      results[[args,blk]] = mthd.bind( self ).(*args, &blk)
    end
  end
  self
end