class FaradayMiddleware::Gzip

Middleware to automatically decompress response bodies. If the “Accept-Encoding” header wasn't set in the request, this sets it to “gzip,deflate” and appropriately handles the compressed response from the server. This resembles what Ruby 1.9+ does internally in Net::HTTP#get.

This middleware is NOT necessary when these adapters are used:

Constants

ACCEPT_ENCODING
CONTENT_ENCODING
CONTENT_LENGTH
RUBY_ENCODING
SUPPORTED_ENCODINGS

Public Instance Methods

call(env) click to toggle source
# File lib/faraday_middleware/gzip.rb, line 22
def call(env)
  env[:request_headers][ACCEPT_ENCODING] ||= SUPPORTED_ENCODINGS
  @app.call(env).on_complete do |response_env|
    case response_env[:response_headers][CONTENT_ENCODING]
    when 'gzip'
      reset_body(response_env, &method(:uncompress_gzip))
    when 'deflate'
      reset_body(response_env, &method(:inflate))
    end
  end
end
inflate(body) click to toggle source
# File lib/faraday_middleware/gzip.rb, line 50
def inflate(body)
  Zlib::Inflate.inflate(body)
end
reset_body(env) { |env| ... } click to toggle source
# File lib/faraday_middleware/gzip.rb, line 34
def reset_body(env)
  env[:body] = yield(env[:body])
  env[:response_headers].delete(CONTENT_ENCODING)
  env[:response_headers][CONTENT_LENGTH] = env[:body].length
end
uncompress_gzip(body) click to toggle source
# File lib/faraday_middleware/gzip.rb, line 40
def uncompress_gzip(body)
  io = StringIO.new(body)
  gzip_reader = if RUBY_ENCODING
    Zlib::GzipReader.new(io, :encoding => 'ASCII-8BIT')
  else
    Zlib::GzipReader.new(io)
  end
  gzip_reader.read
end