module HTTPX::Plugins::ResponseCache::ResponseMethods

  1. lib/httpx/plugins/response_cache.rb

Methods

Public Class

  1. new

Public Instance

  1. cache_control
  2. copy_from_cached!
  3. fresh?
  4. revalidated_at
  5. vary

Attributes

Public Class methods

new(*)
[show source]
    # File lib/httpx/plugins/response_cache.rb
170 def initialize(*)
171   super
172   @revalidated_at = nil
173 end

Public Instance methods

cache_control()

returns the “cache-control” directives as an Array of String(s).

[show source]
    # File lib/httpx/plugins/response_cache.rb
227 def cache_control
228   return @cache_control if defined?(@cache_control)
229 
230   @cache_control = begin
231     @headers["cache-control"].split(/ *, */) if @headers.key?("cache-control")
232   end
233 end
copy_from_cached!()

eager-copies the response headers and body from {RequestMethods#cached_response}.

[show source]
    # File lib/httpx/plugins/response_cache.rb
176 def copy_from_cached!
177   cached_response = @request.cached_response
178 
179   return unless cached_response
180 
181   # 304 responses do not have content-type, which are needed for decoding.
182   @headers = @headers.class.new(cached_response.headers.merge(@headers))
183 
184   @body = cached_response.body.dup
185 
186   @body.rewind
187 
188   cached_response.revalidated_at = date
189 end
fresh?()

A response is fresh if its age has not yet exceeded its freshness lifetime. other (cache_control} directives may influence the outcome, as per the rules from the rfc

[show source]
    # File lib/httpx/plugins/response_cache.rb
194 def fresh?
195   if cache_control
196     return false if cache_control.include?("no-cache")
197 
198     return true if cache_control.include?("immutable")
199 
200     # check age: max-age
201     max_age = cache_control.find { |directive| directive.start_with?("s-maxage") }
202 
203     max_age ||= cache_control.find { |directive| directive.start_with?("max-age") }
204 
205     max_age = max_age[/age=(\d+)/, 1] if max_age
206 
207     max_age = max_age.to_i if max_age
208 
209     return max_age > age if max_age
210   end
211 
212   # check age: expires
213   if @headers.key?("expires")
214     begin
215       expires = Time.httpdate(@headers["expires"])
216     rescue ArgumentError
217       return false
218     end
219 
220     return (expires - Time.now).to_i.positive?
221   end
222 
223   false
224 end
vary()

returns the “vary” header value as an Array of (String) headers.

[show source]
    # File lib/httpx/plugins/response_cache.rb
236 def vary
237   return @vary if defined?(@vary)
238 
239   @vary = begin
240     @headers["vary"].split(/ *, */).map(&:downcase) if @headers.key?("vary")
241   end
242 end