Class: Module

Inherits:
Object show all
Includes:
CacheMethods
Defined in:
lib/tins/memoize.rb,
lib/tins/xt/named.rb

Direct Known Subclasses

Tins::NullClass

Instance Method Summary collapse

Instance Method Details

#memoize_function(*function_ids) ⇒ Object

Automatically memoize calls of the functions function_ids. The memoized result does ONLY depend on the arguments given to the function.



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/tins/memoize.rb', line 46

def memoize_function(*function_ids)
  function_ids.extend(ExtractLastArgumentOptions)
  function_ids, opts = function_ids.extract_last_argument_options
  mc = __memoize_cache__
  function_ids.each do |method_id|
    method_id = method_id.to_s.to_sym
    orig_method = instance_method(method_id)
    __send__(:define_method, method_id) do |*args|
      if mc.key?(method_id) and result = mc[method_id][args]
        result
      else
        (mc[method_id] ||= {})[args] = result = orig_method.bind(self).call(*args)
        opts[:freeze] and result.freeze
        $DEBUG and warn "#{self.class} cached function #{method_id}(#{args.inspect unless args.empty?}) = #{result.inspect}"
      end
      result
    end
  end
end

#memoize_method(*method_ids) ⇒ Object

Automatically memoize calls of the the methods method_ids. The memoized results do NOT ONLY depend on the arguments, but ALSO on the object the method is called on.



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/tins/memoize.rb', line 20

def memoize_method(*method_ids)
  method_ids.extend(ExtractLastArgumentOptions)
  method_ids, opts = method_ids.extract_last_argument_options
  include CacheMethods
  method_ids.each do |method_id|
    method_id = method_id.to_s.to_sym
    orig_method = instance_method(method_id)
    __send__(:define_method, method_id) do |*args|
      mc = __memoize_cache__
      if mc.key?(method_id) and result = mc[method_id][args]
        result
      else
        (mc[method_id] ||= {})[args] = result = orig_method.bind(self).call(*args)
        $DEBUG and warn "#{self.class} cached method #{method_id}(#{args.inspect unless args.empty?}) = #{result.inspect} [#{__id__}]"
        opts[:freeze] and result.freeze
      end
      result
    end
  end
end

#named(name, method, *args, &block) ⇒ Object



22
23
24
25
26
27
28
29
# File 'lib/tins/xt/named.rb', line 22

def named(name, method, *args, &named_block)
  include Module.new {
    define_method(name) do |*rest, &block|
      block = named_block if named_block
      __send__(method, *(args + rest), &block)
    end
  }
end