Module: HTTParty::Cache::Request

Defined in:
lib/httparty/cache/request.rb

Overview

Extends HTTParty::Request with caching methods

Constant Summary collapse

SENSITIVE_HEADERS =
%w[cookie authorization date signature].freeze
CACHE_REVALIDATION_HEADERS =
{
  'ETag' => 'If-None-Match',
  'Last-Modified' => 'If-Modified-Since'
}.freeze

Instance Method Summary collapse

Instance Method Details

#cache_keyString

Calculates a cache key from URI + query string + headers

Returns:

  • (String)


20
21
22
23
24
25
26
# File 'lib/httparty/cache/request.rb', line 20

def cache_key
  @cache_key ||=
    begin
      key = "#{uri}##{URI.encode_www_form(cache_params)}"
      "httpparty-cache:request:#{Digest::SHA2.hexdigest(key)}"
    end
end

#cache_paramsHash

Returns:

  • (Hash)


29
30
31
32
33
# File 'lib/httparty/cache/request.rb', line 29

def cache_params
  return { 'x-cache-key' => options[:cache_key] } if options.key? :cache_key

  options[:headers].to_h.transform_keys(&:downcase).except(*SENSITIVE_HEADERS)
end

#cacheable?Boolean

A cacheable request

Returns:

  • (Boolean)


44
45
46
# File 'lib/httparty/cache/request.rb', line 44

def cacheable?
  caching? && http_method == Net::HTTP::Get
end

#cached_responseHTTParty::Response

Returns:

  • (HTTParty::Response)


81
82
83
# File 'lib/httparty/cache/request.rb', line 81

def cached_response
  @cached_response ||= cache_store.get(cache_store.get(cache_key))
end

#caching?Boolean

Returns:

  • (Boolean)


76
77
78
# File 'lib/httparty/cache/request.rb', line 76

def caching?
  !!options[:caching]
end

#perform(&block) ⇒ HTTParty::Response

Patch HTTParty::Request#perform to provide caching for GET requests

Returns:

  • (HTTParty::Response)


52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/httparty/cache/request.rb', line 52

def perform(&block)
  return super(&block) unless cacheable?

  if response_cached?
    handle_revalidation(&block)
  else
    super(&block).tap do |response|
      # Point current request to cached response
      cache_store.set(response.cache_key, response)
      cache_store.set(cache_key, response.cache_key)
    end
  end
end

#response_cached?Bool

When the request is performed for the first time or has been evicted from cache or is corrupted

Returns:

  • (Bool)


70
71
72
73
74
# File 'lib/httparty/cache/request.rb', line 70

def response_cached?
  cache_store.key?(cache_key) &&
    cache_store.key?(cache_store.get(cache_key)) &&
    cached_response.is_a?(HTTParty::Response)
end

#validateObject

Raises:

  • (ArgumentError)


35
36
37
38
39
# File 'lib/httparty/cache/request.rb', line 35

def validate
  super

  raise ArgumentError, 'Caching is enabled but store was not provided' if caching? && cache_store.nil?
end