class LHC::Caching

Constants

CACHE_VERSION
FORWARDED_OPTIONS

Options forwarded to the cache

Public Instance Methods

after_response(response) click to toggle source
# File lib/lhc-core-interceptors/caching.rb, line 23
def after_response(response)
  return unless cache
  request = response.request
  return if !request.options[:cache] || !response.success?
  cache.write(key(request), to_cache(response), options(request.options))
end
before_request(request) click to toggle source
# File lib/lhc-core-interceptors/caching.rb, line 14
def before_request(request)
  return unless cache
  return unless request.options[:cache]
  cached_response_data = cache.fetch(key(request))
  return unless cached_response_data
  logger.info "Served from cache: #{key(request)}" if logger
  from_cache(request, cached_response_data)
end

Private Instance Methods

from_cache(request, data) click to toggle source

converts json we read from the cache to an LHC::Response object

# File lib/lhc-core-interceptors/caching.rb, line 33
def from_cache(request, data)
  raw = Typhoeus::Response.new(data)
  request.response = LHC::Response.new(raw, request)
end
key(request) click to toggle source
# File lib/lhc-core-interceptors/caching.rb, line 50
def key(request)
  key = request.options[:cache_key]
  unless key
    key = "#{request.method.upcase} #{request.url}"
    key += "?#{request.params.to_query}" unless request.params.blank?
  end
  "LHC_CACHE(v#{CACHE_VERSION}): #{key}"
end
options(input = {}) click to toggle source
# File lib/lhc-core-interceptors/caching.rb, line 59
def options(input = {})
  options = {}
  FORWARDED_OPTIONS.each do |k, v|
    options[v] = input[k] if input.key?(k)
  end
  options
end
to_cache(response) click to toggle source

converts a LHC::Response object to json, we store in the cache

# File lib/lhc-core-interceptors/caching.rb, line 39
def to_cache(response)
  data = {}
  data[:body] = response.body
  data[:code] = response.code
  # convert into a actual hash because the typhoeus headers object breaks marshaling
  data[:headers] = response.headers ? Hash[response.headers] : response.headers
  # return_code is quite important as Typhoeus relies on it in order to determin 'success?'
  data[:return_code] = response.options[:return_code]
  data
end