class TinyClient::Response
Wrap the curl request response.
Attributes
Public Class Methods
# File lib/tiny_client/response.rb, line 9 def initialize(curb) @url = curb.url @body_str = curb.body_str @header_str = curb.header_str @status = curb.status @code = @status.to_i end
Public Instance Methods
@return true if the HTTP status code of this response correspond to an client error.
# File lib/tiny_client/response.rb, line 52 def client_error? (400..499).cover?(@code) end
@return true if the HTTP status code of this response correspond to an client or server error.
# File lib/tiny_client/response.rb, line 42 def error? @code >= 400 end
@return true if this response Content-Encoding is gzip
# File lib/tiny_client/response.rb, line 32 def gzip? /Content-Encoding: gzip/ =~ header_str end
@return true if the HTTP status code of this response is 404
# File lib/tiny_client/response.rb, line 47 def not_found_error? @code == 404 end
Convert the response json body into an hash. @return the parsed response body
# File lib/tiny_client/response.rb, line 19 def parse_body body = gzip? ? gzip_decompress : body_str ActiveSupport::JSON.decode(body) if body.present? end
@return true if the HTTP status code of this response correspond to a redirect.
# File lib/tiny_client/response.rb, line 62 def redirect? (300..399).cover?(@code) end
@return true if the HTTP status code of this response correspond to a server error.
# File lib/tiny_client/response.rb, line 57 def server_error? @code >= 500 end
@return true if the http request has been successful.
# File lib/tiny_client/response.rb, line 37 def success? (200..299).cover?(@code) end
@return Hash with url, status, body and headers fields
# File lib/tiny_client/response.rb, line 67 def to_hash { 'url' => url, 'status' => status, 'body' => (parse_body rescue body_str), 'headers' => (parse_headers rescue header_str) } end
@return String of to_hash
# File lib/tiny_client/response.rb, line 77 def to_s to_hash.to_s end
Parse the X-Total-Count header @return [Integer] the value of the X-Total-Count header, or nil if not present
# File lib/tiny_client/response.rb, line 26 def total_count count = header_str[/X-Total-Count: ([0-9]+)/, 1] count.present? ? count.to_i : nil end
Protected Instance Methods
# File lib/tiny_client/response.rb, line 93 def gzip_decompress ActiveSupport::Gzip.decompress(body_str) end
# File lib/tiny_client/response.rb, line 83 def parse_headers {}.tap do |headers| header_str.to_s.each_line do |header| next if header.index(':').nil? key, value = header.split(':', 2) headers[key] = value.to_s.strip end end end