Method: Readthis::Cache#fetch

Defined in:
lib/readthis/cache.rb

#fetch(key, options = {}) {|String| ... } ⇒ Object

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), then ‘nil` will be returned. However, if a block has been passed, that block will be passed the key and executed 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.

Examples:

Typical


cache.write('today', 'Monday')
cache.fetch('today') # => "Monday"
cache.fetch('city')  # => nil

With a block


cache.fetch('city') do
  'Duckburgh'
end

cache.fetch('city') # => "Duckburgh"

Cache Miss


cache.write('today', 'Monday')
cache.fetch('today', force: true) # => nil

Parameters:

  • key (String)

    Key for lookup

  • options (Hash) (defaults to: {})

    Optional overrides

Options Hash (options):

  • :force (Boolean)

    Force a cache miss

Yields:

  • (String)

    Gives a missing key to the block, which is used to generate the missing value



206
207
208
209
210
211
212
213
214
215
216
# File 'lib/readthis/cache.rb', line 206

def fetch(key, options = {})
  options ||= {}
  value = read(key, options) unless options[:force]

  if value.nil? && block_given?
    value = yield(key)
    write(key, value, options)
  end

  value
end