Class: Pipe2me::HTTP::Response

Inherits:
String
  • Object
show all
Defined in:
lib/pipe2me/ext/http.rb

Overview

The HTTP::Response class works like a string, but contains extra “attributes” status and headers, which return the response status and response headers.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(response, url, original_url) ⇒ Response

:nodoc:



85
86
87
88
# File 'lib/pipe2me/ext/http.rb', line 85

def initialize(response, url, original_url) #:nodoc:
  @response, @url, @original_url = response, url, original_url
  super(response.body || "")
end

Instance Attribute Details

#original_urlObject (readonly)

The URL of the original request.



80
81
82
# File 'lib/pipe2me/ext/http.rb', line 80

def original_url
  @original_url
end

#responseObject (readonly)

The response object.



83
84
85
# File 'lib/pipe2me/ext/http.rb', line 83

def response
  @response
end

#urlObject (readonly)

The URL of the final request.



77
78
79
# File 'lib/pipe2me/ext/http.rb', line 77

def url
  @url
end

Instance Method Details

#codeObject Also known as: status

returns the HTTP status code, as an Integer.



108
109
110
# File 'lib/pipe2me/ext/http.rb', line 108

def code
  @response.code.to_i
end

#content_typeObject



123
124
125
# File 'lib/pipe2me/ext/http.rb', line 123

def content_type
  headers["content-type"]
end

#headersObject

returns all headers.



115
116
117
118
119
120
121
# File 'lib/pipe2me/ext/http.rb', line 115

def headers
  @headers ||= {}.tap do |h|
    @response.each_header do |key, value|
      h[key] = value
    end
  end
end

#parseObject



127
128
129
130
131
132
133
134
135
136
# File 'lib/pipe2me/ext/http.rb', line 127

def parse
  case content_type
  when /application\/json/
    require "json" unless defined?(JSON)
    JSON.parse(self)
  else
    UI.warn "#{url}: Cannot parse #{content_type.inspect} response"
    self
  end
end

#valid?Boolean

returns true if the status is in the 2xx range.

Returns:

  • (Boolean)


91
92
93
# File 'lib/pipe2me/ext/http.rb', line 91

def valid?
  (200..299).include? status
end

#validate!Object

returns the response object itself, if it is valid (i.e. has a 2XX status), or raise an Error.



97
98
99
100
101
102
103
104
105
# File 'lib/pipe2me/ext/http.rb', line 97

def validate!
  return self if valid?

  case status
  when 400..499 then raise ResourceNotFound, self
  when 500..599 then raise ServerError, self
  else raise Error, self
  end
end