2012-04-15 12:26:49 +02:00

67 lines
1.7 KiB
Ruby

require 'timeout'
module Faraday
class Adapter
# Sends requests to a Rack app.
#
# Examples
#
# class MyRackApp
# def call(env)
# [200, {'Content-Type' => 'text/html'}, ["hello world"]]
# end
# end
#
# Faraday.new do |conn|
# conn.adapter :rack, MyRackApp
# end
class Rack < Faraday::Adapter
dependency 'rack/test'
begin
require 'system_timer' if RUBY_VERSION < '1.9'
rescue LoadError
warn "Faraday: you may want to install system_timer for reliable timeouts"
ensure
SystemTimer = Timeout unless defined? ::SystemTimer
end
def initialize(faraday_app, rack_app)
super(faraday_app)
mock_session = ::Rack::MockSession.new(rack_app)
@session = ::Rack::Test::Session.new(mock_session)
end
def call(env)
super
rack_env = {
:method => env[:method],
:input => env[:body].respond_to?(:read) ? env[:body].read : env[:body]
}
if env[:request_headers]
env[:request_headers].each do |k,v|
rack_env[k.upcase.gsub('-', '_')] = v
end
end
timeout = env[:request][:timeout] || env[:request][:open_timeout]
response = if timeout
SystemTimer.timeout(timeout, Faraday::Error::TimeoutError) {
execute_request(env, rack_env)
}
else
execute_request(env, rack_env)
end
save_response(env, response.status, response.body, response.headers)
@app.call env
end
def execute_request(env, rack_env)
@session.request(env[:url].to_s, rack_env)
end
end
end
end