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:



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

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.



70
71
72
# File 'lib/pipe2me/ext/http.rb', line 70

def original_url
  @original_url
end

#responseObject (readonly)

The response object.



73
74
75
# File 'lib/pipe2me/ext/http.rb', line 73

def response
  @response
end

#urlObject (readonly)

The URL of the final request.



67
68
69
# File 'lib/pipe2me/ext/http.rb', line 67

def url
  @url
end

Instance Method Details

#codeObject Also known as: status

returns the HTTP status code, as an Integer.



98
99
100
# File 'lib/pipe2me/ext/http.rb', line 98

def code
  @response.code.to_i
end

#content_typeObject



113
114
115
# File 'lib/pipe2me/ext/http.rb', line 113

def content_type
  headers["content-type"]
end

#headersObject

returns all headers.



105
106
107
108
109
110
111
# File 'lib/pipe2me/ext/http.rb', line 105

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

#parseObject



117
118
119
120
121
122
123
124
125
126
# File 'lib/pipe2me/ext/http.rb', line 117

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)


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

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.



87
88
89
90
91
92
93
94
95
# File 'lib/pipe2me/ext/http.rb', line 87

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