Class: Faraday::HttpCache::Storage

Inherits:
Object
  • Object
show all
Defined in:
lib/faraday/http_cache/storage.rb

Overview

Internal: A Wrapper around an ActiveSupport::CacheStore to store responses.

Examples

# Creates a new Storage using a MemCached backend from ActiveSupport.
Faraday::HttpCache::Storage.new(:mem_cache_store)

# Reuse some other instance of a ActiveSupport::CacheStore object.
Faraday::HttpCache::Storage.new(Rails.cache)

# Creates a new Storage using Marshal for serialization.
Faraday::HttpCache::Storage.new(:memory_store, serializer: Marshal)

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Storage

Internal: Initialize a new Storage object with a cache backend.

options - Storage options (default: {}).

:logger        - A Logger object to be used to emit warnings.
:store         - An cache store object that should
                 respond to 'dump' and 'load'.
:serializer    - A serializer object that should
                 respond to 'dump' and 'load'.
:store_options - An array containg the options for
                 the cache store.


28
29
30
31
32
33
34
35
36
37
# File 'lib/faraday/http_cache/storage.rb', line 28

def initialize(options = {})
  @cache = options[:store] || MemoryStore.new
  @serializer = options[:serializer] || JSON
  @logger = options[:logger]
  if @cache.is_a? Symbol
    @cache = lookup_store(@cache, options[:store_options])
  end
  assert_valid_store!
  notify_memory_store_usage
end

Instance Method Details

#read(request, klass = Faraday::HttpCache::Response) ⇒ Object

Internal: Reads a key based on the given request from the underlying cache.

request - The Hash containing the request information.

:method          - The HTTP Method used for the request.
:url             - The requested URL.
:request_headers - The custom headers for the request.

klass - The Class to be instantiated with the recovered informations.



59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/faraday/http_cache/storage.rb', line 59

def read(request, klass = Faraday::HttpCache::Response)
  cache_key = cache_key_for(request)
  found = @cache.read(cache_key)

  if found
    payload = @serializer.load(found).each_with_object({}) do |(key,value), hash|
      hash[key.to_sym] = value
    end

    klass.new(payload)
  end
end

#write(request, response) ⇒ Object

Internal: Writes a response with a key based on the given request.

request - The Hash containing the request information.

:method          - The HTTP Method used for the request.
:url             - The requested URL.
:request_headers - The custom headers for the request.

response - The Faraday::HttpCache::Response instance to be stored.



46
47
48
49
50
# File 'lib/faraday/http_cache/storage.rb', line 46

def write(request, response)
  key = cache_key_for(request)
  value = @serializer.dump(response.serializable_hash)
  @cache.write(key, value)
end