Skip to content

Commit

Permalink
handle http redirects
Browse files Browse the repository at this point in the history
  • Loading branch information
Adam Wiggins committed Mar 9, 2008
1 parent 77848df commit 0de9892
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
15 changes: 12 additions & 3 deletions lib/rest_client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ def self.delete(url)
####

def self.do_request(method, url, payload=nil)
do_request_inner(method, url, payload)
rescue Redirect => e
do_request(method, e.message, payload)
end

def self.do_request_inner(method, url, payload=nil)
uri = parse_url(url)
transmit uri, net_http_class(method).new(uri.path, headers), payload
end
Expand All @@ -35,18 +41,21 @@ def self.parse_url(url)
URI.parse(url)
end

class Redirect < Exception; end
class RequestFailed < Exception; end
class Unauthorized < Exception; end

def self.transmit(uri, req, payload)
Net::HTTP.start(uri.host, uri.port) do |http|
process_result http.request(req, payload || "")
end
end

class RequestFailed < Exception; end
class Unauthorized < Exception; end

def self.process_result(res)
if %w(200 201 202).include? res.code
res.body
elsif %w(301 302 303).include? res.code
raise Redirect, res.header['Location']
elsif res.code == "401"
raise Unauthorized
else
Expand Down
7 changes: 6 additions & 1 deletion spec/rest_client_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@
RestClient.should_receive(:net_http_class).with(:put).and_return(klass)
klass.should_receive(:new).with('/resource', RestClient.headers).and_return('result')
RestClient.should_receive(:transmit).with(@uri, 'result', 'payload')
RestClient.do_request(:put, 'http://some/resource', 'payload')
RestClient.do_request_inner(:put, 'http://some/resource', 'payload')
end

it "transmits the request with Net::HTTP" do
Expand All @@ -87,5 +87,10 @@
RestClient.should_receive(:process_result)
RestClient.transmit(@uri, 'req', nil)
end

it "do_request calls do_request_inner" do
RestClient.should_receive(:do_request_inner).with(:get, 'http://some/where', 'payload')
RestClient.do_request(:get, 'http://some/where', 'payload')
end
end
end

0 comments on commit 0de9892

Please sign in to comment.