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
-
#cache_key ⇒ String
Calculates a cache key from URI + query string + headers.
- #cache_params ⇒ Hash
-
#cacheable? ⇒ Boolean
A cacheable request.
- #cached_response ⇒ HTTParty::Response
- #caching? ⇒ Boolean
-
#perform(&block) ⇒ HTTParty::Response
Patch HTTParty::Request#perform to provide caching for GET requests.
-
#response_cached? ⇒ Bool
When the request is performed for the first time or has been evicted from cache or is corrupted.
- #validate ⇒ Object
Instance Method Details
#cache_key ⇒ String
Calculates a cache key from URI + query string + headers
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_params ⇒ Hash
29 30 31 32 33 |
# File 'lib/httparty/cache/request.rb', line 29 def cache_params return { 'x-cache-key' => [:cache_key] } if .key? :cache_key [:headers].to_h.transform_keys(&:downcase).except(*SENSITIVE_HEADERS) end |
#cacheable? ⇒ Boolean
A cacheable request
44 45 46 |
# File 'lib/httparty/cache/request.rb', line 44 def cacheable? caching? && http_method == Net::HTTP::Get end |
#cached_response ⇒ 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
76 77 78 |
# File 'lib/httparty/cache/request.rb', line 76 def caching? !![:caching] end |
#perform(&block) ⇒ HTTParty::Response
Patch HTTParty::Request#perform to provide caching for GET requests
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
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 |
#validate ⇒ Object
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 |