Class: HTTP::Features::AutoDeflate

Inherits:
HTTP::Feature show all
Defined in:
lib/http/features/auto_deflate.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeAutoDeflate

Returns a new instance of AutoDeflate.

Raises:



10
11
12
13
14
15
16
# File 'lib/http/features/auto_deflate.rb', line 10

def initialize(*)
  super

  @method = @opts.key?(:method) ? @opts[:method].to_s : "gzip"

  raise Error, "Only gzip and deflate methods are supported" unless %w(gzip deflate).include?(@method)
end

Instance Attribute Details

#methodObject (readonly)

Returns the value of attribute method.



8
9
10
# File 'lib/http/features/auto_deflate.rb', line 8

def method
  @method
end

Instance Method Details

#deflate(headers, body) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/http/features/auto_deflate.rb', line 18

def deflate(headers, body)
  return body unless body
  return body unless body.is_a?(String)

  # We need to delete Content-Length header. It will be set automatically
  # by HTTP::Request::Writer
  headers.delete(Headers::CONTENT_LENGTH)

  headers[Headers::CONTENT_ENCODING] = method

  case method
  when "gzip" then
    StringIO.open do |out|
      Zlib::GzipWriter.wrap(out) do |gz|
        gz.write body
        gz.finish
        out.tap(&:rewind).read
      end
    end
  when "deflate" then
    Zlib::Deflate.deflate(body)
  else
    raise ArgumentError, "Unsupported deflate method: #{method}"
  end
end