class Attune::Gzip

Some code taken from a yet to be released version of faraday-middleware

Constants

ACCEPT_ENCODING
CONTENT_ENCODING
CONTENT_LENGTH
CONTENT_TYPE
ENCODING_TYPE
MIME_TYPE
RUBY_ENCODING
SUPPORTED_ENCODINGS

Public Instance Methods

call(env) click to toggle source
# File lib/attune/gzip.rb, line 15
def call(env)
  if has_body?(env) && is_json?(env)
    wio = StringIO.new("w")
    w_gz = Zlib::GzipWriter.new(wio)
    w_gz.write env[:body]
    w_gz.close
    env[:body] = wio.string
    env[:request_headers][CONTENT_ENCODING] = ENCODING_TYPE
  end
  env[:request_headers][ACCEPT_ENCODING] ||= SUPPORTED_ENCODINGS
  @app.call(env).on_complete do |env|
    case env[:response_headers][CONTENT_ENCODING]
    when 'gzip'
      reset_body(env, &method(:uncompress_gzip))
    when 'deflate'
      reset_body(env, &method(:inflate))
    end
  end
end
has_body?(env) click to toggle source
# File lib/attune/gzip.rb, line 37
def has_body?(env)
  body = env[:body] and !(body.respond_to?(:to_str) and body.empty?)
end
inflate(body) click to toggle source
# File lib/attune/gzip.rb, line 56
def inflate(body)
  Zlib::Inflate.inflate(body)
end
is_json?(env) click to toggle source
# File lib/attune/gzip.rb, line 34
def is_json?(env)
  env[:request_headers][CONTENT_TYPE] == MIME_TYPE
end
reset_body(env) { |env| ... } click to toggle source
# File lib/attune/gzip.rb, line 41
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/attune/gzip.rb, line 47
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