Class: BraintreeHttp::Encoder

Inherits:
Object
  • Object
show all
Defined in:
lib/braintreehttp/encoder.rb

Instance Method Summary collapse

Constructor Details

#initializeEncoder

Returns a new instance of Encoder.



10
11
12
# File 'lib/braintreehttp/encoder.rb', line 10

def initialize
  @encoders = [Json.new, Text.new, Multipart.new, FormEncoded.new]
end

Instance Method Details

#_encoder(content_type) ⇒ Object



53
54
55
56
57
# File 'lib/braintreehttp/encoder.rb', line 53

def _encoder(content_type)
  idx = @encoders.index { |enc| enc.content_type.match(content_type) }

  @encoders[idx] if idx
end

#_extract_header(headers, key) ⇒ Object



59
60
61
62
63
64
# File 'lib/braintreehttp/encoder.rb', line 59

def _extract_header(headers, key)
  value = headers[key] || headers[key.downcase]
  value = value.first if value.kind_of?(Array)

  value
end

#deserialize_response(resp, headers) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/braintreehttp/encoder.rb', line 32

def deserialize_response(resp, headers)
  raise UnsupportedEncodingError.new('HttpResponse did not have Content-Type header set') unless headers && (headers['content-type'] || headers['Content-Type'])

  content_type = _extract_header(headers, 'Content-Type')

  enc = _encoder(content_type)
  raise UnsupportedEncodingError.new("Unable to deserialize response with Content-Type #{content_type}. Supported decodings are #{supported_encodings}") unless enc

  content_encoding = _extract_header(headers, 'Content-Encoding')

  if content_encoding == 'gzip'
    resp = Zlib::Inflate.inflate(resp)
  end

  enc.decode(resp)
end

#serialize_request(req) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/braintreehttp/encoder.rb', line 14

def serialize_request(req)
  raise UnsupportedEncodingError.new('HttpRequest did not have Content-Type header set') unless req.headers && (req.headers['content-type'] || req.headers['Content-Type'])

  content_type = _extract_header(req.headers, 'Content-Type')

  enc = _encoder(content_type)
  raise UnsupportedEncodingError.new("Unable to serialize request with Content-Type #{content_type}. Supported encodings are #{supported_encodings}") unless enc

  encoded = enc.encode(req)
  content_encoding = _extract_header(req.headers, 'Content-Encoding')

  if content_encoding == 'gzip'
    encoded = Zlib::Deflate.deflate(encoded)
  end

  encoded
end

#supported_encodingsObject



49
50
51
# File 'lib/braintreehttp/encoder.rb', line 49

def supported_encodings
  @encoders.map { |enc| enc.content_type.inspect }
end