Method: Lemo::Ormo::ClassMethods#ormo

Defined in:
lib/lemo/ormo.rb

#ormo(meth) ⇒ Object Also known as: memo

WARNING race condition if two threads concurrently define the same memo’ed method on the same class. Unlikely, but still.



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/lemo/ormo.rb', line 25

def ormo( 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

  # keep this for initial calculation, and recalculation
  memoed_methods[meth] = unbound_previous_method
  ivar = ivar_from meth

  # Define the class using instance variable @ syntax, for fastest
  # runtime. Use class_eval to define an instance method, cos self is the
  # class (or singleton class) right now
  class_eval <<-RUBY, __FILE__, __LINE__
    def #{meth}
      #{ivar} ||= _memoed_methods[:#{meth}].bind(self).call
    end
  RUBY

  # allow chaining of symbol returned from def
  meth
end