Class: HttpRequest::Response

Inherits:
Object
  • Object
show all
Defined in:
lib/http-request/response.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(net_http_response, request_uri) ⇒ Response

Returns a new instance of Response.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/http-request/response.rb', line 5

def initialize(net_http_response, request_uri)
  @status       = net_http_response.code.to_i
  @body         = net_http_response.body
  @raw          = net_http_response
  @request_uri  = request_uri

  @header = net_http_response.header.to_hash.tap do |header|
    header.each {|k,v| header[k] = v.first if v.is_a?(Array) && v.length == 1 }
  end

  # Auto decompress content
  content_encoding = @header['content-encoding'].to_s.downcase
  if !content_encoding.empty? && content_encoding =~ /gzip/
    gz = Zlib::GzipReader.new(StringIO.new(@body), :external_encoding => @body.encoding)
    @body = gz.read
  end

  # Content type handling
  content_type = @header['content-type'].to_s
  charset = content_type.match(/charset=([a-z0-9-]*)/i).to_s
  if !charset.empty?
    # Encode to suggested charset
    encoding = Encoding.find(charset.split('=')[1]) rescue nil
    @body.force_encoding(encoding) if !encoding.nil?
  else
    # Encode to utf-8 by default for any ascii content types
    # that don't specify the charset
    # mime_type = MIME::Types[content_type].first
    # @body.force_encoding('utf-8') if mime_type && mime_type.ascii?
  end
end

Instance Attribute Details

#bodyObject (readonly)

Returns the value of attribute body.



3
4
5
# File 'lib/http-request/response.rb', line 3

def body
  @body
end

#headerObject (readonly)

Returns the value of attribute header.



3
4
5
# File 'lib/http-request/response.rb', line 3

def header
  @header
end

#rawObject (readonly)

Returns the value of attribute raw.



3
4
5
# File 'lib/http-request/response.rb', line 3

def raw
  @raw
end

#request_uriObject (readonly)

Returns the value of attribute request_uri.



3
4
5
# File 'lib/http-request/response.rb', line 3

def request_uri
  @request_uri
end

#statusObject (readonly)

Returns the value of attribute status.



3
4
5
# File 'lib/http-request/response.rb', line 3

def status
  @status
end

Instance Method Details

#status_messageObject



37
38
39
# File 'lib/http-request/response.rb', line 37

def status_message
  "#{status} #{raw.message}"
end