module Lemo::Ormo::ClassMethods

Public Instance Methods

ivar_from( meth ) click to toggle source

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.

# File lib/lemo/ormo.rb, line 19
def ivar_from( meth )
  :"@#{meth.to_s.delete ILLEGAL_IVAR_CHARS}"
end
memo( meth )

for all the things using memo already

Alias for: ormo
memoed_methods() click to toggle source
# File lib/lemo/ormo.rb, line 12
def memoed_methods
  @memoed_methods ||= {}
end
ormo( meth ) click to toggle source

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

# 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
Also aliased as: memo