Module: HTTPX::Plugins::ResponseCache::ResponseMethods

Defined in:
lib/httpx/plugins/response_cache.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#revalidated_at=(value) ⇒ Object (writeonly)

Sets the attribute revalidated_at

Parameters:

  • value

    the value to set the attribute revalidated_at to.



168
169
170
# File 'lib/httpx/plugins/response_cache.rb', line 168

def revalidated_at=(value)
  @revalidated_at = value
end

Instance Method Details

#cache_controlObject

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



227
228
229
230
231
232
233
# File 'lib/httpx/plugins/response_cache.rb', line 227

def cache_control
  return @cache_control if defined?(@cache_control)

  @cache_control = begin
    @headers["cache-control"].split(/ *, */) if @headers.key?("cache-control")
  end
end

#copy_from_cached!Object

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



176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/httpx/plugins/response_cache.rb', line 176

def copy_from_cached!
  cached_response = @request.cached_response

  return unless cached_response

  # 304 responses do not have content-type, which are needed for decoding.
  @headers = @headers.class.new(cached_response.headers.merge(@headers))

  @body = cached_response.body.dup

  @body.rewind

  cached_response.revalidated_at = date
end

#fresh?Boolean

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

Returns:

  • (Boolean)


194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/httpx/plugins/response_cache.rb', line 194

def fresh?
  if cache_control
    return false if cache_control.include?("no-cache")

    return true if cache_control.include?("immutable")

    # check age: max-age
    max_age = cache_control.find { |directive| directive.start_with?("s-maxage") }

    max_age ||= cache_control.find { |directive| directive.start_with?("max-age") }

    max_age = max_age[/age=(\d+)/, 1] if max_age

    max_age = max_age.to_i if max_age

    return max_age > age if max_age
  end

  # check age: expires
  if @headers.key?("expires")
    begin
      expires = Time.httpdate(@headers["expires"])
    rescue ArgumentError
      return false
    end

    return (expires - Time.now).to_i.positive?
  end

  false
end

#initializeObject



170
171
172
173
# File 'lib/httpx/plugins/response_cache.rb', line 170

def initialize(*)
  super
  @revalidated_at = nil
end

#varyObject

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



236
237
238
239
240
241
242
# File 'lib/httpx/plugins/response_cache.rb', line 236

def vary
  return @vary if defined?(@vary)

  @vary = begin
    @headers["vary"].split(/ *, */).map(&:downcase) if @headers.key?("vary")
  end
end