Module: Rip::Memoize

Included in:
Installer, Package, TestMemoize::Encoder
Defined in:
lib/rip/memoize.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



4
5
6
# File 'lib/rip/memoize.rb', line 4

def self.included(base)
  base.extend self
end

Instance Method Details

#memoize(method) ⇒ Object



8
9
10
11
# File 'lib/rip/memoize.rb', line 8

def memoize(method)
  @memoized ||= {}
  @memoized[method] = true
end

#method_added(method) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/rip/memoize.rb', line 13

def method_added(method)
  @memoized ||= {}
  return unless @memoized.delete(method)

  real_name = "__memoized_#{method}"
  alias_method real_name, method

  if self.instance_method(method).arity == 0
    define_method method do
      if instance_variable_defined? ivar = "@#{method}"
        instance_variable_get ivar
      else
        instance_variable_set ivar, send(real_name)
      end
    end
  else
    define_method method do |*args|
      @memoize_cache ||= {}
      key = [method, args].hash

      if @memoize_cache.has_key?(key)
        @memoize_cache[key]
      else
        @memoize_cache[key] = send(real_name, *args)
      end
    end
  end
end