class Totter::Transport::HTTP::Response

Response class responsible for deserializing API calls @attr [Object] body The parsed response @attr [Hash] headers HTTP headers returned as part of the response

Attributes

body[RW]
headers[RW]

Public Class Methods

new(http_response, result_format = :mashie) click to toggle source

Initializes a new result

@param http_response [Net::HTTPResponse] the raw response to parse

# File lib/totter/transport/http.rb, line 131
def initialize(http_response, result_format = :mashie)
  @result_format = result_format
  @headers = parse_headers(http_response.to_hash)
  @body = parse_body(http_response.body)
end

Private Instance Methods

parse_body(body) click to toggle source

Parses the raw body in to a Hashie::Mash object, an array of Hashie::Mashes, or, if all else fails, returns a hash.

# File lib/totter/transport/http.rb, line 149
def parse_body(body)
  # Parse JSON
  object = MultiJson.load(body)

  case @result_format
  when :mashie
    # Hash
    return Hashie::Mash.new(object) if object.is_a? Hash
    # Array
    begin
      return object.map { |h| Hashie::Mash.new(h) } if object.is_a? Array
    rescue
      # sometimes, for things like string arrays, we'll end up with an error. Fall through.
    end
  end

  object
end
parse_headers(raw_headers) click to toggle source

Parses raw headers in to a reasonable hash

# File lib/totter/transport/http.rb, line 140
def parse_headers(raw_headers)
  # raw headers from net_http have an array for each result. Flatten them out.
  raw_headers.inject({}) do |remainder, (k, v)|
    remainder[k] = [v].flatten.first
    remainder
  end
end