diff --git a/lib/rest_client.rb b/lib/rest_client.rb index 3f9ce58..c759d8b 100644 --- a/lib/rest_client.rb +++ b/lib/rest_client.rb @@ -42,8 +42,8 @@ module RestClient def initialize(args) @method = args[:method] or raise ArgumentError, "must pass :method" @url = args[:url] or raise ArgumentError, "must pass :url" - @payload = args[:payload] @headers = args[:headers] || {} + @payload = process_payload(args[:payload]) @user = args[:user] @password = args[:password] end @@ -87,6 +87,15 @@ module RestClient # Authorization is required to access the resource specified. class Unauthorized < Exception; end + def process_payload(p=nil) + if p && p.is_a?( Hash ) && method == :post + @headers[:content_type] = 'application/x-www-form-urlencoded' + p.keys.collect{|k| "#{k}=#{URI.escape(p[k])}"}.join("&") + else + p + end + end + def transmit(uri, req, payload) setup_credentials(req) diff --git a/spec/rest_client_spec.rb b/spec/rest_client_spec.rb index 94bfcf6..109790e 100644 --- a/spec/rest_client_spec.rb +++ b/spec/rest_client_spec.rb @@ -22,6 +22,28 @@ describe RestClient do RestClient.delete('http://some/resource') end end + + context "RestClient with a hash of form data as a payload" do + before do + @request = RestClient::Request.new(:method => :post, :url => 'http://some/resource', :payload => {:email => "my@email.com", :password =>"secrets"}) + @uri = mock("uri") + @uri.stub!(:request_uri).and_return('/resource') + @uri.stub!(:host).and_return('some') + @uri.stub!(:port).and_return(80) + Net::HTTP::Post.stub!(:new).and_return(@net = mock('Net::HTTP::Post')) + @request.stub!(:transmit) + end + + it "should set the payload to be the hash processed into URI params" do + @request.should_receive(:transmit).with(URI.parse('http://some/resource'), @net, "email=my@email.com&password=secrets") + @request.execute_inner + end + + it "should add the 'application/x-www-form-urlencoded' content_type header" do + @request.should_receive(:make_headers).with({:content_type => 'application/x-www-form-urlencoded'}) + @request.execute_inner + end + end context RestClient::Request do before do @@ -139,3 +161,5 @@ describe RestClient do end end end + +