Method: ActiveRestClient::Caching::ClassMethods#write_cached_response

Defined in:
lib/active_rest_client/caching.rb

#write_cached_response(request, response, result) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/active_rest_client/caching.rb', line 55

def write_cached_response(request, response, result)
  return if result.is_a? Symbol
  return unless perform_caching
  return unless !result.respond_to?(:_status) || [200, 304].include?(result._status)
  headers = response.response_headers

  headers.keys.select{|h| h.is_a? String}.each do |key|
    headers[key.downcase.to_sym] = headers[key]
  end

  if cache_store && (headers[:etag] || headers[:expires])
    key = "#{request.class_name}:#{request.original_url}"
    ActiveRestClient::Logger.debug "  \033[1;4;32m#{ActiveRestClient::NAME}\033[0m #{key} - Writing to cache"
    cached_response = CachedResponse.new(status:response.status, result:result)
    cached_response.etag = headers[:etag] if headers[:etag]
    cached_response.expires = Time.parse(headers[:expires]) rescue nil if headers[:expires]
    cache_store.write(key, Marshal.dump(cached_response), {}) if cached_response.etag.present? || cached_response.expires
  end
end