Class: HTTP::Features::AutoDeflate

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

Overview

Automatically compresses request bodies with gzip or deflate

Defined Under Namespace

Classes: CompressedBody, DeflatedBody, GzippedBody

Constant Summary collapse

VALID_METHODS =

Supported compression methods

Set.new(%w[gzip deflate]).freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from HTTP::Feature

#around_request, #on_error, #on_request, #wrap_response

Constructor Details

#initialize(method: "gzip") ⇒ AutoDeflate

Initializes the AutoDeflate feature

Examples:

AutoDeflate.new(method: "gzip")

Parameters:

  • method (String) (defaults to: "gzip")

    compression method (“gzip” or “deflate”)

Raises:



32
33
34
35
36
37
38
# File 'lib/http/features/auto_deflate.rb', line 32

def initialize(method: "gzip")
  super()

  @method = String(method)

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

Instance Attribute Details

#methodString (readonly)

Compression method name

Examples:

feature.method # => "gzip"

Returns:

  • (String)

    compression method name



22
23
24
# File 'lib/http/features/auto_deflate.rb', line 22

def method
  @method
end

Instance Method Details

#deflated_body(body) ⇒ GzippedBody, ...

Returns a compressed body for the given body

Examples:

feature.deflated_body(body)

Parameters:

Returns:



67
68
69
70
71
72
73
74
# File 'lib/http/features/auto_deflate.rb', line 67

def deflated_body(body)
  case method
  when "gzip"
    GzippedBody.new(body)
  when "deflate"
    DeflatedBody.new(body)
  end
end

#wrap_request(request) ⇒ HTTP::Request

Wraps a request with compressed body

Examples:

feature.wrap_request(request)

Parameters:

Returns:



48
49
50
51
52
53
54
55
56
57
# File 'lib/http/features/auto_deflate.rb', line 48

def wrap_request(request)
  return request unless method
  return request if request.body.empty?

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

  build_deflated_request(request)
end