Skip to content

Caching

therabidbanana edited this page Mar 22, 2012 · 7 revisions

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.

Warning: Note that if Faraday is making requests to another server that uses Rack::Cache as middleware, there is currently a header "X-Content-Digest" that will cause Faraday's Rack::Cache to be unable to save anything to the entity store (https://github.com/rtomayko/rack-cache/issues/59).

(Please note: This wiki has been closed, and turned into in-repo Markdown documents. You can find them in the repository's docs/ directory. This wiki does not take new edits.)

Clone this wiki locally