set default Faraday::Connection#path_prefix

This commit is contained in:
rick 2009-12-10 06:08:06 -08:00
parent f5128bad51
commit 637909c690
2 changed files with 20 additions and 11 deletions

View File

@ -8,20 +8,26 @@ module Faraday
def initialize(url = nil) def initialize(url = nil)
if url if url
uri = URI.parse(url) uri = URI.parse(url)
@host = uri.host self.host = uri.host
@port = uri.port self.port = uri.port
@path_prefix = uri.path if !uri.path.empty? self.path_prefix = uri.path
end end
end end
# Override in a subclass, or include an adapter
#
# def _get(uri, headers)
# end
#
def get(url, params = {}, headers = {}) def get(url, params = {}, headers = {})
_get(build_uri(url, params), headers) _get(build_uri(url, params), headers)
end end
def path_prefix=(value) def path_prefix=(value)
if value if value
value.chomp! "/" value.chomp! "/"
value.replace "/#{value}" if value !~ /^\// value.replace "/#{value}" if value !~ /^\//
end end
@path_prefix = value @path_prefix = value
@ -32,7 +38,7 @@ module Faraday
uri.host ||= @host uri.host ||= @host
uri.port ||= @port uri.port ||= @port
if @path_prefix && uri.path !~ /^\// if @path_prefix && uri.path !~ /^\//
uri.path = "#{@path_prefix}/#{uri.path}" uri.path = "#{@path_prefix.size > 1 ? @path_prefix : nil}/#{uri.path}"
end end
uri.query = params_to_query(params) uri.query = params_to_query(params)
uri uri
@ -43,9 +49,5 @@ module Faraday
memo << "#{URI.escape(key)}=#{URI.escape(val)}" memo << "#{URI.escape(key)}=#{URI.escape(val)}"
end.join("&") end.join("&")
end end
def _get(uri, headers)
raise NotImplementedError
end
end end
end end

View File

@ -19,7 +19,7 @@ class ConnectionTest < Faraday::TestCase
it "parses nil @path_prefix out of given url" do it "parses nil @path_prefix out of given url" do
conn = TestConnection.new "http://sushi.com" conn = TestConnection.new "http://sushi.com"
assert_nil conn.path_prefix assert_equal '/', conn.path_prefix
end end
it "parses @path_prefix out of given url" do it "parses @path_prefix out of given url" do
@ -50,6 +50,13 @@ class ConnectionTest < Faraday::TestCase
assert_equal '/fish/sake.html', uri.path assert_equal '/fish/sake.html', uri.path
end end
it "uses '/' Connection#path_prefix to customize the path" do
conn = TestConnection.new
conn.path_prefix = '/'
uri = conn.build_uri("sake.html")
assert_equal '/sake.html', uri.path
end
it "forces Connection#path_prefix to be absolute" do it "forces Connection#path_prefix to be absolute" do
conn = TestConnection.new conn = TestConnection.new
conn.path_prefix = 'fish' conn.path_prefix = 'fish'