Module: Lemo::Ormo::ClassMethods

Defined in:
lib/lemo/ormo.rb

Instance Method Summary collapse

Instance Method Details

#ivar_from(meth) ⇒ Object

provide a legal ivar name from a method name. instance variables can’t have ? ! and other punctuation. Which isn’t handled. Obviously. WARNING meth, meth? and meth! will access the same ivar.



19
20
21
# File 'lib/lemo/ormo.rb', line 19

def ivar_from( meth )
  :"@#{meth.to_s.delete ILLEGAL_IVAR_CHARS}"
end

#memoed_methodsObject



12
13
14
# File 'lib/lemo/ormo.rb', line 12

def memoed_methods
  @memoed_methods ||= {}
end

#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 "    def \#{meth}\n      \#{ivar} ||= _memoed_methods[:\#{meth}].bind(self).call\n    end\n  RUBY\n\n  # allow chaining of symbol returned from def\n  meth\nend\n", __FILE__, __LINE__