allow options to Faraday::Connection#new, set default headers/params for requests

This commit is contained in:
rick 2009-12-22 12:44:32 -08:00
parent ae381e1217
commit d70413af87
2 changed files with 43 additions and 5 deletions

View File

@ -12,11 +12,21 @@ module Faraday
include Addressable
attr_accessor :host, :port, :scheme
attr_accessor :host, :port, :scheme, :params, :headers
attr_reader :path_prefix
def initialize(url = nil)
@response_class = nil
# :url
# :params
# :headers
# :response
def initialize(url = nil, options = {})
if url.is_a?(Hash)
options = url
url = options[:url]
end
@response_class = options[:response]
@params = options[:params] || {}
@headers = options[:headers] || {}
self.url_prefix = url if url
end
@ -33,8 +43,9 @@ module Faraday
# def _get(uri, headers)
# end
#
def get(url, params = {}, headers = {})
_get(build_uri(url, params), headers)
def get(url, params = nil, headers = nil)
uri = build_uri(url, build_params(params))
_get(uri, build_headers(headers))
end
def response_class
@ -85,6 +96,18 @@ module Faraday
uri
end
def build_params(existing)
build_hash :params, existing
end
def build_headers(existing)
build_hash :headers, existing
end
def build_hash(method, existing)
existing ? send(method).merge(existing) : send(method)
end
def params_to_query(params)
params.inject([]) do |memo, (key, val)|
memo << "#{escape_for_querystring(key)}=#{escape_for_querystring(val)}"

View File

@ -31,6 +31,21 @@ class ConnectionTest < Faraday::TestCase
conn = Faraday::Connection.new "http://sushi.com/fish"
assert_equal '/fish', conn.path_prefix
end
it "parses @path_prefix out of given url option" do
conn = Faraday::Connection.new :url => "http://sushi.com/fish"
assert_equal '/fish', conn.path_prefix
end
it "stores default params from options" do
conn = Faraday::Connection.new :params => {:a => 1}
assert_equal 1, conn.params[:a]
end
it "stores default headers from options" do
conn = Faraday::Connection.new :headers => {:a => 1}
assert_equal 1, conn.headers[:a]
end
end
describe "#build_uri" do