Class: Faraday::HttpCache::Strategies::ByVary

Inherits:
BaseStrategy
  • Object
show all
Defined in:
lib/faraday/http_cache/strategies/by_vary.rb

Overview

This strategy uses headers from the Vary response header to generate cache keys. It also uses the index with Vary headers mapped to the request url. This strategy is more suitable for caching private responses with the same urls, like api.github.com/user.

This strategy does not support #delete method to clear cache on unsafe methods.

Instance Attribute Summary

Attributes inherited from BaseStrategy

#cache

Instance Method Summary collapse

Methods inherited from BaseStrategy

#initialize

Constructor Details

This class inherits a constructor from Faraday::HttpCache::Strategies::BaseStrategy

Instance Method Details

#delete(_url) ⇒ void

This method returns an undefined value.

This strategy does not support #delete method to clear cache on unsafe methods.



56
57
58
# File 'lib/faraday/http_cache/strategies/by_vary.rb', line 56

def delete(_url)
  # do nothing since we can't find the key by url
end

#read(request) ⇒ Faraday::HttpCache::Response?

Fetch a stored response that suits the incoming HTTP request or return nil.

Parameters:

Returns:



42
43
44
45
46
47
48
49
50
51
52
# File 'lib/faraday/http_cache/strategies/by_vary.rb', line 42

def read(request)
  vary_cache_key = vary_cache_key_for(request)
  vary = cache.read(vary_cache_key)
  return nil if vary.nil? || vary == '*'

  cache_key = response_cache_key_for(request, vary)
  response = cache.read(cache_key)
  return nil if response.nil?

  Faraday::HttpCache::Response.new(deserialize_object(response))
end

#write(request, response) ⇒ void

This method returns an undefined value.

Store a response inside the cache.

Parameters:



23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/faraday/http_cache/strategies/by_vary.rb', line 23

def write(request, response)
  vary_cache_key = vary_cache_key_for(request)
  headers = Faraday::Utils::Headers.new(response.payload[:response_headers])
  vary = headers['Vary'].to_s
  cache.write(vary_cache_key, vary)

  response_cache_key = response_cache_key_for(request, vary)
  entry = serialize_object(response.serializable_hash)
  cache.write(response_cache_key, entry)
rescue ::Encoding::UndefinedConversionError => e
  warn "Response could not be serialized: #{e.message}. Try using Marshal to serialize."
  raise e
end