instance method fetch

Ruby on Rails 2.3.18

Since v2.2.3

Available in: v2.2.3 v2.3.18 v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

fetch(key, options = {})

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 :force => true 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

Parameters

key req
options opt = {}
Source
# File activesupport/lib/active_support/cache.rb, line 151
      def fetch(key, options = {})
        @logger_off = true
        if !options[:force] && value = read(key, options)
          @logger_off = false
          log("hit", key, options)
          value
        elsif block_given?
          @logger_off = false
          log("miss", key, options)

          value = nil
          ms = Benchmark.ms { value = yield }

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

          log('write (will save %.2fms)' % ms, key, nil)

          value
        end
      end

Defined in activesupport/lib/active_support/cache.rb line 151 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveSupport::Cache::Store

Type at least 2 characters to search.

↑↓ navigate · open · esc close