Class: Sinew::Response

Inherits:
Object show all
Defined in:
lib/sinew/response.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#bodyObject

Returns the value of attribute body.



10
11
12
# File 'lib/sinew/response.rb', line 10

def body
  @body
end

#codeObject

Returns the value of attribute code.



10
11
12
# File 'lib/sinew/response.rb', line 10

def code
  @code
end

#headersObject

Returns the value of attribute headers.



10
11
12
# File 'lib/sinew/response.rb', line 10

def headers
  @headers
end

#requestObject

Returns the value of attribute request.



10
11
12
# File 'lib/sinew/response.rb', line 10

def request
  @request
end

#uriObject

Returns the value of attribute uri.



10
11
12
# File 'lib/sinew/response.rb', line 10

def uri
  @uri
end

Class Method Details

.from_network(request, fday_response) ⇒ Object

factory methods



16
17
18
19
20
21
22
23
24
# File 'lib/sinew/response.rb', line 16

def self.from_network(request, fday_response)
  Response.new.tap do
    _1.request = request
    _1.uri = fday_response.env.url
    _1.code = fday_response.status
    _1.headers = fday_response.headers.to_h
    _1.body = process_body(fday_response)
  end
end

.process_body(response) ⇒ Object

helper for decoding bodies before parsing



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/sinew/response.rb', line 27

def self.process_body(response)
  body = response.body

  # inflate if necessary
  bits = body[0, 10].force_encoding('BINARY')
  if bits =~ /\A\x1f\x8b/n
    body = Zlib::GzipReader.new(StringIO.new(body)).read
  end

  # force to utf-8 if we think this could be text
  if body.encoding != Encoding::UTF_8
    if content_type = response.headers['content-type']
      if content_type =~ /\b(html|javascript|json|text|xml)\b/
        body = body.encode('UTF-8', invalid: :replace, undef: :replace, replace: '?')
      end
    end
  end

  body
end

Instance Method Details

#error?Boolean

accessors

Returns:

  • (Boolean)


52
53
54
# File 'lib/sinew/response.rb', line 52

def error?
  code >= 400
end

#error_500?Boolean

Returns:

  • (Boolean)


56
57
58
# File 'lib/sinew/response.rb', line 56

def error_500?
  code / 100 >= 5
end

#head_as_jsonObject



64
65
66
67
68
69
70
# File 'lib/sinew/response.rb', line 64

def head_as_json
  {
    uri: uri,
    code: code,
    headers: headers,
  }
end

#redirected?Boolean

Returns:

  • (Boolean)


60
61
62
# File 'lib/sinew/response.rb', line 60

def redirected?
  request.uri != uri
end