Class: Attune::Gzip

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/attune/gzip.rb

Overview

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

Constant Summary collapse

CONTENT_TYPE =
'Content-Type'.freeze
CONTENT_ENCODING =
'Content-Encoding'.freeze
MIME_TYPE =
'application/json'.freeze
ENCODING_TYPE =
'gzip'.freeze
ACCEPT_ENCODING =
'Accept-Encoding'.freeze
CONTENT_LENGTH =
'Content-Length'.freeze
SUPPORTED_ENCODINGS =
'gzip,deflate'.freeze
RUBY_ENCODING =
'1.9'.respond_to?(:force_encoding)

Instance Method Summary collapse

Instance Method Details

#call(env) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# 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) ⇒ Boolean

Returns:

  • (Boolean)


37
38
39
# 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) ⇒ Object



56
57
58
# File 'lib/attune/gzip.rb', line 56

def inflate(body)
  Zlib::Inflate.inflate(body)
end

#is_json?(env) ⇒ Boolean

Returns:

  • (Boolean)


34
35
36
# File 'lib/attune/gzip.rb', line 34

def is_json?(env)
  env[:request_headers][CONTENT_TYPE] == MIME_TYPE
end

#reset_body(env) ⇒ Object



41
42
43
44
45
# 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) ⇒ Object



47
48
49
50
51
52
53
54
55
# 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