class Patron::Response

Represents the response from the HTTP server.

Attributes

body[R]
charset[R]
headers[R]
redirect_count[R]
status[R]
status_line[R]
url[R]

Public Class Methods

new(url, status, redirect_count, header_data, body, default_charset = nil) click to toggle source
# File lib/patron/response.rb, line 31
def initialize(url, status, redirect_count, header_data, body, default_charset = nil)
  # Don't let a response clear out the default charset, which would cause encoding to fail
  default_charset = "ASCII-8BIT" unless default_charset
  @url            = url
  @status         = status
  @redirect_count = redirect_count
  @body           = body

  @charset        = determine_charset(header_data, body) || default_charset

  [url, header_data].each do |attr|
    convert_to_default_encoding!(attr)
  end

  parse_headers(header_data)
  if @headers["Content-Type"] && @headers["Content-Type"][0, 5] == "text/"
    convert_to_default_encoding!(@body)
  end
end

Public Instance Methods

inspect() click to toggle source
# File lib/patron/response.rb, line 53
def inspect
  # Avoid spamming the console with the header and body data
  "#<Patron::Response @status_line='#{@status_line}'>"
end
marshal_dump() click to toggle source
# File lib/patron/response.rb, line 58
def marshal_dump
  [@url, @status, @status_line, @redirect_count, @body, @headers, @charset]
end
marshal_load(data) click to toggle source
# File lib/patron/response.rb, line 62
def marshal_load(data)
  @url, @status, @status_line, @redirect_count, @body, @headers, @charset = data
end

Private Instance Methods

charset_regex() click to toggle source
# File lib/patron/response.rb, line 74
def charset_regex
  /(?:charset|encoding)="?([a-z0-9-]+)"?/
end
convert_to_default_encoding!(str) click to toggle source
# File lib/patron/response.rb, line 78
def convert_to_default_encoding!(str)
  if str.respond_to?(:encode) && Encoding.default_internal
    str.force_encoding(charset).encode!(Encoding.default_internal)
  end
end
determine_charset(header_data, body) click to toggle source
# File lib/patron/response.rb, line 68
def determine_charset(header_data, body)
  header_data.match(charset_regex) || (body && body.match(charset_regex))

  $1
end
parse_headers(header_data) click to toggle source

Called by the C code to parse and set the headers

# File lib/patron/response.rb, line 85
def parse_headers(header_data)
  @headers = {}

  header_data.split(/\r\n/).each do |header|
    if header =~ %r^HTTP/1.[01]|
      @status_line = header.strip
    else
      parts = header.split(':', 2)
      unless parts.empty?
        parts[1].strip! unless parts[1].nil?
        if @headers.has_key?(parts[0])
          @headers[parts[0]] = [@headers[parts[0]]] unless @headers[parts[0]].kind_of? Array
          @headers[parts[0]] << parts[1]
        else
          @headers[parts[0]] = parts[1]
        end
      end
    end
  end
end