Skip to content
Mislav Marohnić edited this page Jan 24, 2012 · 1 revision

Caching responses

Simple response body caching

FaradayMiddleware::Caching can be configured with a cache store that responds to read, write and fetch, such as one of ActiveSupport::Cache stores.

Example use:

conn.response :caching, :ignore_params => %w[access_token] do
  cache_dir = File.join(ENV['TMPDIR'], 'cache')
  ActiveSupport::Cache::FileStore.new cache_dir, :namespace => 'my_namespace',
    :expires_in => 3600  # one hour
end

In the above example, the return value of the block represents the cache store that the middleware will use. It's configured to cache each GET response for 1 hour.

Advanced HTTP caching

FaradayMiddleware::RackCompatible can be used to mount rack-cache to the middleware stack in order to perform caching per HTTP spec.

conn.use FaradayMiddleware::RackCompatible, Rack::Cache::Context,
  :metastore   => "file:#{cache_dir}/rack/meta",
  :entitystore => "file:#{cache_dir}/rack/body",

In the above example, the stack is configured to cache successful responses to disk according to HTTP freshness/expiration information, and subsequent requests will be validated using information in Last-Modified/ETag headers.