Module: ActiveSupport::Memoizable

Defined in:
lib/gems/activesupport-2.2.2/lib/active_support/memoizable.rb

Defined Under Namespace

Modules: Freezable

Constant Summary collapse

MEMOIZED_IVAR =
Proc.new do |symbol|
  "@_memoized_#{symbol.to_s.sub(/\?\Z/, '_query').sub(/!\Z/, '_bang')}".to_sym
end

Instance Method Summary collapse

Instance Method Details

#memoize(*symbols) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/gems/activesupport-2.2.2/lib/active_support/memoizable.rb', line 44

def memoize(*symbols)
  symbols.each do |symbol|
    original_method = :"_unmemoized_#{symbol}"
    memoized_ivar = MEMOIZED_IVAR.call(symbol)

    class_eval <<-EOS, __FILE__, __LINE__
      include Freezable

      raise "Already memoized #{symbol}" if method_defined?(:#{original_method})
      alias #{original_method} #{symbol}

      if instance_method(:#{symbol}).arity == 0
        def #{symbol}(reload = false)
          if reload || !defined?(#{memoized_ivar}) || #{memoized_ivar}.empty?
            #{memoized_ivar} = [#{original_method}.freeze]
          end
          #{memoized_ivar}[0]
        end
      else
        def #{symbol}(*args)
          #{memoized_ivar} ||= {} unless frozen?
          reload = args.pop if args.last == true || args.last == :reload

          if defined?(#{memoized_ivar}) && #{memoized_ivar}
            if !reload && #{memoized_ivar}.has_key?(args)
              #{memoized_ivar}[args]
            elsif #{memoized_ivar}
              #{memoized_ivar}[args] = #{original_method}(*args).freeze
            end
          else
            #{original_method}(*args)
          end
        end
      end
    EOS
  end
end