Hurley Http Cache
a Hurley connection that respects HTTP cache, by checking expiration and validation of the stored responses. This gem is a direct reimplementation of the faraday-http-cache gem.
Installation
Add it to your Gemfile:
gem 'hurley-http-cache'
Usage and configuration
You can use an instance of the Hurley::HttpCache
as the connection for your
hurley
client.
require 'hurley'
require 'hurley/http_cache'
client = Hurley::Client.new
client.connection = Hurley::HttpCache.new
The middleware accepts a store
option for the cache backend responsible for
recording the API responses that should be stored. Stores should respond to
write
and read
, just like an object from the ActiveSupport::Cache
API.
store = ActiveSupport::Cache.lookup_store(:mem_cache_store, ['localhost:11211'])
client = Hurley::Client.new
# Use the connection with a Memcache server.
client.connection = Hurley::HttpCache.new(store: store)
# Or use the Rails.cache instance inside your Rails app.
client.connection = Hurley::HttpCache.new(store: Rails.cache)
By default, the Hurley::HttpCache
connection will use the Hurley.default_connection
to perform the real HTTP requests when we can't use a cached response. If you
want to use a different connection object, just pass it when creating the
Hurley::HttpCache
object.
require 'hurley'
require 'hurley-excon'
client = Hurley.new
client.connection = Hurley::HttpCache.new(HurleyExcon::Connection.new)
The default store provided is a simple in memory cache that lives on the client instance. This type of store might not be persisted across multiple processes or connection instances so it is probably not suitable for most production environments. Make sure that you configure a store that is suitable for you.
the stdlib JSON
module is used for serialization by default.
If you expect to be dealing with images, you can use [Marshal][http://ruby-doc.org//core-2.2.0/Marshal.html]
instead, or if you want to use another json library like oj
or yajl-ruby
.
client = Hurley::Client.new
client.connection = Hurley::HttpCache.new(store: Rails.cache, serializer: Marshal)
Logging
You can provide a logger
option that will be receive debug informations based
connection operations:
client = Hurley::Client.new
client.connection = Hurley::HttpCache.new(logger: Rails.logger)
client.get('http://site/api/users')
# logs "HTTP Cache: [GET /users] miss, store"
See it live
You can clone this repository, install it's dependencies with Bundler (run bundle install
) and
execute the files under the examples
directory to see a sample of the gem usage.
License
Copyright (c) 2015 Plataformatec. See LICENSE file.