add more options for passing Faraday::Builder instances around

This commit is contained in:
rick 2010-04-22 12:16:56 -04:00
parent b7eabb95f7
commit 4f9660213f
3 changed files with 43 additions and 15 deletions

View File

@ -9,20 +9,29 @@ module Faraday
class Builder
attr_accessor :handlers
def self.create_with_inner_app(&block)
inner = lambda do |env|
if !env[:parallel_manager]
env[:response].finish(env)
else
env[:response]
end
end
Builder.new(&block).tap { |builder| builder.run(inner) }
def self.create(&block)
Builder.new(&block)
end
def initialize(handlers = [])
def self.inner_app
lambda do |env|
env[:parallel_manager] ? env[:response] : env[:response].finish(env)
end
end
def initialize(handlers = [], &block)
@handlers = handlers
yield self if block_given?
build(&block) if block_given?
end
def build(&block)
block.call(self)
run(self.class.inner_app)
end
def [](index)
# @handlers are stored in reverse order
@handlers[-(index+1)]
end
def run(app)
@ -35,7 +44,7 @@ module Faraday
end
def use(klass, *args, &block)
@handlers.unshift(lambda { |app| klass.new(app, *args, &block) })
run(lambda { |app| klass.new(app, *args, &block) })
end
def request(key, *args, &block)

View File

@ -33,12 +33,16 @@ module Faraday
merge_params @params, options[:params] if options[:params]
merge_headers @headers, options[:headers] if options[:headers]
if block
@builder = Builder.create_with_inner_app(&block)
@builder = Builder.create(&block)
else
@builder = options[:builder] || Builder.new
end
end
def build(&block)
@builder.build(&block)
end
def get(url = nil, headers = nil, &block)
run_request :get, url, nil, headers, &block
end

View File

@ -35,11 +35,26 @@ class TestConnectionApps < Faraday::TestCase
end
def test_builder_adds_middleware_to_builder_stack
assert_kind_of TestMiddleWare, @conn.builder.handlers[2].call(nil)
assert_kind_of TestAdapter, @conn.builder.handlers[1].call(nil)
assert_kind_of TestMiddleWare, @conn.builder[0].call(nil)
assert_kind_of TestAdapter, @conn.builder[1].call(nil)
end
def test_to_app_returns_rack_object
assert @conn.to_app.respond_to?(:call)
end
def test_builder_is_passed_to_new_faraday_connection
new_conn = Faraday::Connection.new :builder => @conn.builder
assert_equal @conn.builder, new_conn.builder
end
def test_builder_is_built_on_new_faraday_connection
new_conn = Faraday::Connection.new
new_conn.build do |b|
b.run @conn.builder[0]
b.run @conn.builder[1]
end
assert_kind_of TestMiddleWare, new_conn.builder[0].call(nil)
assert_kind_of TestAdapter, new_conn.builder[1].call(nil)
end
end