Class: Faraday::HttpCache::Strategies::ByUrl

Inherits:
BaseStrategy show all
Defined in:
lib/faraday/http_cache/strategies/by_url.rb

Overview

The original strategy by Faraday::HttpCache. Uses URL + HTTP method to generate cache keys.

Direct Known Subclasses

Faraday::HttpCache::Storage

Instance Attribute Summary

Attributes inherited from BaseStrategy

#cache

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ ByUrl

Returns a new instance of ByUrl.



13
14
15
16
# File 'lib/faraday/http_cache/strategies/by_url.rb', line 13

def initialize(options = {})
  super
  @max_entries = options[:max_entries]
end

Instance Method Details

#delete(url) ⇒ void

This method returns an undefined value.

Parameters:

  • url (String)

    – the url of a changed resource, will be used to invalidate the cache.



59
60
61
62
# File 'lib/faraday/http_cache/strategies/by_url.rb', line 59

def delete(url)
  cache_key = cache_key_for(url)
  cache.delete(cache_key)
end

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

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

Parameters:

Returns:



47
48
49
50
51
52
53
54
# File 'lib/faraday/http_cache/strategies/by_url.rb', line 47

def read(request)
  cache_key = cache_key_for(request.url)
  entries = cache.read(cache_key)
  response = lookup_response(request, entries)
  return nil unless response

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

#write(request, response) ⇒ void

This method returns an undefined value.

Store a response inside the cache.

Parameters:



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/faraday/http_cache/strategies/by_url.rb', line 24

def write(request, response)
  key = cache_key_for(request.url)
  entry = serialize_entry(request.serializable_hash, response.serializable_hash)
  entries = cache.read(key) || []
  entries = entries.dup if entries.frozen?
  entries.reject! do |(cached_request, cached_response)|
    response_matches?(request, deserialize_object(cached_request), deserialize_object(cached_response))
  end

  entries << entry
  entries = entries.last(@max_entries) unless @max_entries.nil?

  cache.write(key, entries)
rescue ::Encoding::UndefinedConversionError => e
  warn "Response could not be serialized: #{e.message}. Try using Marshal to serialize."
  raise e
end