cache.rb 7.8 KB
Newer Older
1 2
require 'benchmark'

3
module ActiveSupport
P
Pratik Naik 已提交
4
  # See ActiveSupport::Cache::Store for documentation.
5
  module Cache
J
Jeremy Kemper 已提交
6 7 8 9 10 11 12
    autoload :FileStore, 'active_support/cache/file_store'
    autoload :MemoryStore, 'active_support/cache/memory_store'
    autoload :SynchronizedMemoryStore, 'active_support/cache/synchronized_memory_store'
    autoload :DRbStore, 'active_support/cache/drb_store'
    autoload :MemCacheStore, 'active_support/cache/mem_cache_store'
    autoload :CompressedMemCacheStore, 'active_support/cache/compressed_mem_cache_store'

13 14 15 16
    module Strategy
      autoload :LocalCache, 'active_support/cache/strategy/local_cache'
    end

P
Pratik Naik 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
    # Creates a new CacheStore object according to the given options.
    #
    # If no arguments are passed to this method, then a new
    # ActiveSupport::Cache::MemoryStore object will be returned.
    #
    # If you pass a Symbol as the first argument, then a corresponding cache
    # store class under the ActiveSupport::Cache namespace will be created.
    # For example:
    #
    #   ActiveSupport::Cache.lookup_store(:memory_store)
    #   # => returns a new ActiveSupport::Cache::MemoryStore object
    #   
    #   ActiveSupport::Cache.lookup_store(:drb_store)
    #   # => returns a new ActiveSupport::Cache::DRbStore object
    #
    # Any additional arguments will be passed to the corresponding cache store
    # class's constructor:
    #
    #   ActiveSupport::Cache.lookup_store(:file_store, "/tmp/cache")
    #   # => same as: ActiveSupport::Cache::FileStore.new("/tmp/cache")
    #
    # If the first argument is not a Symbol, then it will simply be returned:
    #
    #   ActiveSupport::Cache.lookup_store(MyOwnCacheStore.new)
    #   # => returns MyOwnCacheStore.new
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
    def self.lookup_store(*store_option)
      store, *parameters = *([ store_option ].flatten)

      case store
      when Symbol
        store_class_name = (store == :drb_store ? "DRbStore" : store.to_s.camelize)
        store_class = ActiveSupport::Cache.const_get(store_class_name)
        store_class.new(*parameters)
      when nil
        ActiveSupport::Cache::MemoryStore.new
      else
        store
      end
    end

    def self.expand_cache_key(key, namespace = nil)
      expanded_cache_key = namespace ? "#{namespace}/" : ""
59

60
      if ENV["RAILS_CACHE_ID"] || ENV["RAILS_APP_VERSION"]
61
        expanded_cache_key << "#{ENV["RAILS_CACHE_ID"] || ENV["RAILS_APP_VERSION"]}/"
62 63 64
      end

      expanded_cache_key << case
65 66 67 68
        when key.respond_to?(:cache_key)
          key.cache_key
        when key.is_a?(Array)
          key.collect { |element| expand_cache_key(element) }.to_param
J
Jeremy Kemper 已提交
69
        when key
70 71
          key.to_param
        end.to_s
72 73 74 75

      expanded_cache_key
    end

P
Pratik Naik 已提交
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
    # An abstract cache store class. There are multiple cache store
    # implementations, each having its own additional features. See the classes
    # under the ActiveSupport::Cache module, e.g.
    # ActiveSupport::Cache::MemCacheStore. MemCacheStore is currently the most
    # popular cache store for large production websites.
    #
    # ActiveSupport::Cache::Store is meant for caching strings. Some cache
    # store implementations, like MemoryStore, are able to cache arbitrary
    # Ruby objects, but don't count on every cache store to be able to do that.
    #
    #   cache = ActiveSupport::Cache::MemoryStore.new
    #   
    #   cache.read("city")   # => nil
    #   cache.write("city", "Duckburgh")
    #   cache.read("city")   # => "Duckburgh"
91 92 93
    class Store
      cattr_accessor :logger

94 95 96 97 98
      def silence!
        @silence = true
        self
      end

P
Pratik Naik 已提交
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
      # Fetches data from the cache, using the given key. If there is data in
      # the cache with the given key, then that data is returned.
      #
      # If there is no such data in the cache (a cache miss occurred), then
      # then nil will be returned. However, if a block has been passed, then
      # that block will be run in the event of a cache miss. The return value
      # of the block will be written to the cache under the given cache key,
      # and that return value will be returned.
      #
      #   cache.write("today", "Monday")
      #   cache.fetch("today")  # => "Monday"
      #   
      #   cache.fetch("city")   # => nil
      #   cache.fetch("city") do
      #     "Duckburgh"
      #   end
      #   cache.fetch("city")   # => "Duckburgh"
      #
      # You may also specify additional options via the +options+ argument.
      # Setting <tt>:force => true</tt> will force a cache miss:
      #
      #   cache.write("today", "Monday")
      #   cache.fetch("today", :force => true)  # => nil
      #
      # Other options will be handled by the specific cache store implementation.
      # Internally, #fetch calls #read, and calls #write on a cache miss.
      # +options+ will be passed to the #read and #write calls.
      #
      # For example, MemCacheStore's #write method supports the +:expires_in+
      # option, which tells the memcached server to automatically expire the
      # cache item after a certain period. We can use this option with #fetch
      # too:
      #
      #   cache = ActiveSupport::Cache::MemCacheStore.new
      #   cache.fetch("foo", :force => true, :expires_in => 5.seconds) do
      #     "bar"
      #   end
      #   cache.fetch("foo")  # => "bar"
      #   sleep(6)
      #   cache.fetch("foo")  # => nil
139 140
      def fetch(key, options = {})
        @logger_off = true
141
        if !options[:force] && value = read(key, options)
142 143 144 145 146 147 148 149
          @logger_off = false
          log("hit", key, options)
          value
        elsif block_given?
          @logger_off = false
          log("miss", key, options)

          value = nil
J
Jeremy Kemper 已提交
150
          ms = Benchmark.ms { value = yield }
151 152 153 154 155

          @logger_off = true
          write(key, value, options)
          @logger_off = false

J
Jeremy Kemper 已提交
156
          log('write (will save %.2fms)' % ms, key, nil)
157 158 159 160 161

          value
        end
      end

P
Pratik Naik 已提交
162 163 164 165 166 167 168
      # Fetches data from the cache, using the given key. If there is data in
      # the cache with the given key, then that data is returned. Otherwise,
      # nil is returned.
      #
      # You may also specify additional options via the +options+ argument.
      # The specific cache store implementation will decide what to do with
      # +options+.
169 170 171 172
      def read(key, options = nil)
        log("read", key, options)
      end

P
Pratik Naik 已提交
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
      # Writes the given value to the cache, with the given key.
      #
      # You may also specify additional options via the +options+ argument.
      # The specific cache store implementation will decide what to do with
      # +options+.
      # 
      # For example, MemCacheStore supports the +:expires_in+ option, which
      # tells the memcached server to automatically expire the cache item after
      # a certain period:
      #
      #   cache = ActiveSupport::Cache::MemCacheStore.new
      #   cache.write("foo", "bar", :expires_in => 5.seconds)
      #   cache.read("foo")  # => "bar"
      #   sleep(6)
      #   cache.read("foo")  # => nil
188 189 190 191 192 193 194 195 196 197
      def write(key, value, options = nil)
        log("write", key, options)
      end

      def delete(key, options = nil)
        log("delete", key, options)
      end

      def delete_matched(matcher, options = nil)
        log("delete matched", matcher.inspect, options)
198 199 200 201 202 203
      end

      def exist?(key, options = nil)
        log("exist?", key, options)
      end

204 205 206 207 208 209 210
      def increment(key, amount = 1)
        log("incrementing", key, amount)
        if num = read(key)
          write(key, num + amount)
        else
          nil
        end
211 212
      end

213 214 215 216 217 218 219 220
      def decrement(key, amount = 1)
        log("decrementing", key, amount)
        if num = read(key)
          write(key, num - amount)
        else
          nil
        end
      end
221

222 223
      private
        def log(operation, key, options)
224
          logger.debug("Cache #{operation}: #{key}#{options ? " (#{options.inspect})" : ""}") if logger && !@silence && !@logger_off
225 226 227 228
        end
    end
  end
end