Module: Memoized::ClassMethods

Defined in:
lib/memoized.rb

Instance Method Summary collapse

Instance Method Details

#memoize(*method_names) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/memoized.rb', line 20

def memoize(*method_names)
  method_names.each do |method_name|
    memoized_ivar_name = Memoized.ivar_name(method_name)
    unmemoized_method = "_unmemoized_#{method_name}"

    alias_method unmemoized_method, method_name

    parameters = Parameters.new(instance_method(unmemoized_method).parameters)

    module_eval(<<-RUBY)
      def #{method_name}(#{parameters.signature})
        #{parameters.cache_key}

        #{memoized_ivar_name} ||= {}
        
        if #{memoized_ivar_name}.key?(cache_key)
          #{memoized_ivar_name}[cache_key]
        else
          live_result = if all_kwargs.empty?
            #{unmemoized_method}(*all_args)
          else  
            #{unmemoized_method}(*all_args, **all_kwargs)
          end
          #{memoized_ivar_name}[cache_key] = live_result
          live_result
        end
      end
    RUBY

    if self.private_method_defined?(unmemoized_method)
      private method_name
    elsif self.protected_method_defined?(unmemoized_method)
      protected method_name
    end
  end
end