class HTTParty::Decompressor

Decompresses the response body based on the Content-Encoding header.

Net::HTTP automatically decompresses Content-Encoding values “gzip” and “deflate”. This class will handle “br” (Brotli) and “compress” (LZW) if the requisite gems are installed. Otherwise, it returns nil if the body data cannot be decompressed.

@abstract Read the HTTP Compression section for more information.

Constants

SupportedEncodings

“gzip” and “deflate” are handled by Net::HTTP hence they do not need to be handled by HTTParty

Attributes

body[R]

The response body of the request @return [String]

encoding[R]

The Content-Encoding algorithm used to encode the body @return [Symbol] e.g. :gzip

Public Class Methods

new(body, encoding) click to toggle source

@param [String] body - the response body of the request @param [Symbol] encoding - the Content-Encoding algorithm used to encode the body

# File lib/httparty/decompressor.rb, line 33
def initialize(body, encoding)
  @body = body
  @encoding = encoding
end

Public Instance Methods

decompress() click to toggle source

Perform decompression on the response body @return [String] the decompressed body @return [nil] when the response body is nil or cannot decompressed

# File lib/httparty/decompressor.rb, line 41
def decompress
  return nil if body.nil?
  return body if encoding.nil? || encoding.strip.empty?

  if supports_encoding?
    decompress_supported_encoding
  else
    nil
  end
end

Protected Instance Methods

brotli() click to toggle source
# File lib/httparty/decompressor.rb, line 71
def brotli
  return nil unless defined?(::Brotli)
  begin
    ::Brotli.inflate(body)
  rescue StandardError
    nil
  end
end
decompress_supported_encoding() click to toggle source
# File lib/httparty/decompressor.rb, line 58
def decompress_supported_encoding
  method = SupportedEncodings[encoding]
  if respond_to?(method, true)
    send(method)
  else
    raise NotImplementedError, "#{self.class.name} has not implemented a decompression method for #{encoding.inspect} encoding."
  end
end
lzw() click to toggle source
# File lib/httparty/decompressor.rb, line 80
def lzw
  begin
    if defined?(::LZWS::String)
      ::LZWS::String.decompress(body)
    elsif defined?(::LZW::Simple)
      ::LZW::Simple.new.decompress(body)
    end
  rescue StandardError
    nil
  end
end
none() click to toggle source
# File lib/httparty/decompressor.rb, line 67
def none
  body
end
supports_encoding?() click to toggle source
# File lib/httparty/decompressor.rb, line 54
def supports_encoding?
  SupportedEncodings.keys.include?(encoding)
end