fetch(key, options = {}) public

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
Show source
Register or log in to add new notes.