YARD annotations; Git ignore .yardoc/ (#788)

This commit is contained in:
Olle Jonsson 2018-04-17 16:08:09 +02:00 committed by Mattia
parent d9661c4567
commit 89b3365896
17 changed files with 241 additions and 123 deletions

1
.gitignore vendored
View File

@ -20,3 +20,4 @@ vendor/bundle
## IDEs ## IDEs
.idea/ .idea/
.yardoc/

View File

@ -1,5 +1,5 @@
module Faraday module Faraday
# Public: This is a base class for all Faraday adapters. Adapters are # Base class for all Faraday adapters. Adapters are
# responsible for fulfilling a Faraday request. # responsible for fulfilling a Faraday request.
class Adapter < Middleware class Adapter < Middleware
CONTENT_LENGTH = 'Content-Length'.freeze CONTENT_LENGTH = 'Content-Length'.freeze
@ -16,7 +16,7 @@ module Faraday
:rack => [:Rack, 'rack'], :rack => [:Rack, 'rack'],
:httpclient => [:HTTPClient, 'httpclient'] :httpclient => [:HTTPClient, 'httpclient']
# Public: This module marks an Adapter as supporting parallel requests. # This module marks an Adapter as supporting parallel requests.
module Parallelism module Parallelism
attr_writer :supports_parallel attr_writer :supports_parallel
def supports_parallel?() @supports_parallel end def supports_parallel?() @supports_parallel end

View File

@ -1,10 +1,11 @@
module Faraday module Faraday
class Adapter class Adapter
# EventMachine adapter is useful for either asynchronous requests # EventMachine adapter. This adapter is useful for either asynchronous
# when in EM reactor loop or for making parallel requests in # requests when in an EM reactor loop, or for making parallel requests in
# synchronous code. # synchronous code.
class EMHttp < Faraday::Adapter class EMHttp < Faraday::Adapter
module Options module Options
# @return [Hash]
def connection_config(env) def connection_config(env)
options = {} options = {}
configure_proxy(options, env) configure_proxy(options, env)
@ -30,6 +31,7 @@ module Faraday
body.respond_to?(:read) ? body.read : body body.respond_to?(:read) ? body.read : body
end end
# Reads out proxy settings from env into options
def configure_proxy(options, env) def configure_proxy(options, env)
if proxy = request_options(env)[:proxy] if proxy = request_options(env)[:proxy]
options[:proxy] = { options[:proxy] = {
@ -40,6 +42,7 @@ module Faraday
end end
end end
# Reads out host and port settings from env into options
def configure_socket(options, env) def configure_socket(options, env)
if bind = request_options(env)[:bind] if bind = request_options(env)[:bind]
options[:bind] = { options[:bind] = {
@ -49,6 +52,7 @@ module Faraday
end end
end end
# Reads out SSL certificate settings from env into options
def configure_ssl(options, env) def configure_ssl(options, env)
if env[:url].scheme == 'https' && env[:ssl] if env[:url].scheme == 'https' && env[:ssl]
options[:ssl] = { options[:ssl] = {
@ -58,12 +62,14 @@ module Faraday
end end
end end
# Reads out timeout settings from env into options
def configure_timeout(options, env) def configure_timeout(options, env)
timeout, open_timeout = request_options(env).values_at(:timeout, :open_timeout) timeout, open_timeout = request_options(env).values_at(:timeout, :open_timeout)
options[:connect_timeout] = options[:inactivity_timeout] = timeout options[:connect_timeout] = options[:inactivity_timeout] = timeout
options[:connect_timeout] = open_timeout if open_timeout options[:connect_timeout] = open_timeout if open_timeout
end end
# Reads out compression header settings from env into options
def configure_compression(options, env) def configure_compression(options, env)
if env[:method] == :get and not options[:head].key? 'accept-encoding' if env[:method] == :get and not options[:head].key? 'accept-encoding'
options[:head]['accept-encoding'] = 'gzip, compressed' options[:head]['accept-encoding'] = 'gzip, compressed'
@ -81,6 +87,7 @@ module Faraday
self.supports_parallel = true self.supports_parallel = true
# @return [Manager]
def self.setup_parallel_manager(options = nil) def self.setup_parallel_manager(options = nil)
Manager.new Manager.new
end end
@ -176,17 +183,20 @@ module Faraday
raise errklass, msg raise errklass, msg
end end
# @return [Boolean]
def parallel?(env) def parallel?(env)
!!env[:parallel_manager] !!env[:parallel_manager]
end end
# The parallel manager is designed to start an EventMachine loop # This parallel manager is designed to start an EventMachine loop
# and block until all registered requests have been completed. # and block until all registered requests have been completed.
class Manager class Manager
# @see reset
def initialize def initialize
reset reset
end end
# Re-initializes instance variables
def reset def reset
@registered_procs = [] @registered_procs = []
@num_registered = 0 @num_registered = 0
@ -195,6 +205,7 @@ module Faraday
@running = false @running = false
end end
# @return [Boolean]
def running?() @running end def running?() @running end
def add def add

View File

@ -1,6 +1,7 @@
require 'openssl' require 'openssl'
require 'em-http' require 'em-http'
# EventMachine patch to make SSL work.
module EmHttpSslPatch module EmHttpSslPatch
def ssl_verify_peer(cert_string) def ssl_verify_peer(cert_string)
cert = nil cert = nil

View File

@ -2,6 +2,7 @@ require 'uri'
module Faraday module Faraday
class Adapter class Adapter
# EventMachine Synchrony adapter.
class EMSynchrony < Faraday::Adapter class EMSynchrony < Faraday::Adapter
include EMHttp::Options include EMHttp::Options
@ -13,6 +14,7 @@ module Faraday
self.supports_parallel = true self.supports_parallel = true
# @return [ParallelManager]
def self.setup_parallel_manager(options = {}) def self.setup_parallel_manager(options = {})
ParallelManager.new ParallelManager.new
end end

View File

@ -1,10 +1,14 @@
module Faraday module Faraday
class Adapter class Adapter
class EMSynchrony < Faraday::Adapter class EMSynchrony < Faraday::Adapter
# A parallel manager for EMSynchrony.
class ParallelManager class ParallelManager
# Add requests to queue. The `request` argument should be a # Add requests to queue.
# `EM::HttpRequest` object. #
# @param request [EM::HttpRequest]
# @param method [Symbol, String] HTTP method
# @param args [Array] the rest of the positional arguments
def add(request, method, *args, &block) def add(request, method, *args, &block)
queue << { queue << {
:request => request, :request => request,
@ -60,7 +64,7 @@ module Faraday
multi.perform multi.perform
end end
end # ParallelManager end
end # EMSynchrony end
end # Adapter end
end # Faraday end

View File

@ -1,5 +1,6 @@
module Faraday module Faraday
class Adapter class Adapter
# Excon adapter.
class Excon < Faraday::Adapter class Excon < Faraday::Adapter
dependency 'excon' dependency 'excon'
@ -70,6 +71,7 @@ module Faraday
raise Error::TimeoutError, err raise Error::TimeoutError, err
end end
# @return [Excon]
def create_connection(env, opts) def create_connection(env, opts)
::Excon.new(env[:url].to_s, opts.merge(@connection_options)) ::Excon.new(env[:url].to_s, opts.merge(@connection_options))
end end

View File

@ -1,8 +1,10 @@
module Faraday module Faraday
class Adapter class Adapter
# HTTPClient adapter.
class HTTPClient < Faraday::Adapter class HTTPClient < Faraday::Adapter
dependency 'httpclient' dependency 'httpclient'
# @return [HTTPClient]
def client def client
@client ||= ::HTTPClient.new @client ||= ::HTTPClient.new
end end
@ -64,11 +66,15 @@ module Faraday
end end
end end
# @param bind [Hash]
def configure_socket(bind) def configure_socket(bind)
client.socket_local.host = bind[:host] client.socket_local.host = bind[:host]
client.socket_local.port = bind[:port] client.socket_local.port = bind[:port]
end end
# Configure proxy URI and any user credentials.
#
# @param proxy [Hash]
def configure_proxy(proxy) def configure_proxy(proxy)
client.proxy = proxy[:uri] client.proxy = proxy[:uri]
if proxy[:user] && proxy[:password] if proxy[:user] && proxy[:password]
@ -76,6 +82,7 @@ module Faraday
end end
end end
# @param ssl [Hash]
def configure_ssl(ssl) def configure_ssl(ssl)
ssl_config = client.ssl_config ssl_config = client.ssl_config
ssl_config.verify_mode = ssl_verify_mode(ssl) ssl_config.verify_mode = ssl_verify_mode(ssl)
@ -88,6 +95,7 @@ module Faraday
ssl_config.verify_depth = ssl[:verify_depth] if ssl[:verify_depth] ssl_config.verify_depth = ssl[:verify_depth] if ssl[:verify_depth]
end end
# @param req [Hash]
def configure_timeouts(req) def configure_timeouts(req)
if req[:timeout] if req[:timeout]
client.connect_timeout = req[:timeout] client.connect_timeout = req[:timeout]
@ -105,6 +113,8 @@ module Faraday
@config_block.call(client) if @config_block @config_block.call(client) if @config_block
end end
# @param ssl [Hash]
# @return [OpenSSL::X509::Store]
def ssl_cert_store(ssl) def ssl_cert_store(ssl)
return ssl[:cert_store] if ssl[:cert_store] return ssl[:cert_store] if ssl[:cert_store]
# Memoize the cert store so that the same one is passed to # Memoize the cert store so that the same one is passed to
@ -118,6 +128,7 @@ module Faraday
end end
end end
# @param ssl [Hash]
def ssl_verify_mode(ssl) def ssl_verify_mode(ssl)
ssl[:verify_mode] || begin ssl[:verify_mode] || begin
if ssl.fetch(:verify, true) if ssl.fetch(:verify, true)

View File

@ -8,6 +8,7 @@ require 'zlib'
module Faraday module Faraday
class Adapter class Adapter
# Net::HTTP adapter.
class NetHttp < Faraday::Adapter class NetHttp < Faraday::Adapter
NET_HTTP_EXCEPTIONS = [ NET_HTTP_EXCEPTIONS = [
IOError, IOError,

View File

@ -1,5 +1,6 @@
module Faraday module Faraday
class Adapter class Adapter
# Net::HTTP::Persistent adapter.
class NetHttpPersistent < NetHttp class NetHttpPersistent < NetHttp
dependency 'net/http/persistent' dependency 'net/http/persistent'

View File

@ -1,5 +1,6 @@
module Faraday module Faraday
class Adapter class Adapter
# Patron adapter.
class Patron < Faraday::Adapter class Patron < Faraday::Adapter
dependency 'patron' dependency 'patron'
@ -69,6 +70,7 @@ module Faraday
end end
end end
# @return [Patron::Session]
def create_session def create_session
session = ::Patron::Session.new session = ::Patron::Session.new
@config_block.call(session) if @config_block @config_block.call(session) if @config_block

View File

@ -2,7 +2,7 @@ module Faraday
class Adapter class Adapter
# Sends requests to a Rack app. # Sends requests to a Rack app.
# #
# Examples # @example
# #
# class MyRackApp # class MyRackApp
# def call(env) # def call(env)

View File

@ -1,6 +1,6 @@
module Faraday module Faraday
class Adapter class Adapter
# This class is just a stub, the real adapter is in https://github.com/philsturgeon/typhoeus/blob/master/lib/typhoeus/adapters/faraday.rb # Typhoeus adapter. This class is just a stub, the real adapter is in https://github.com/philsturgeon/typhoeus/blob/master/lib/typhoeus/adapters/faraday.rb
class Typhoeus < Faraday::Adapter class Typhoeus < Faraday::Adapter
# Needs to define this method in order to support Typhoeus <= 1.3.0 # Needs to define this method in order to support Typhoeus <= 1.3.0
def call; end def call; end

View File

@ -1,15 +1,17 @@
module Faraday module Faraday
# Internal: Adds the ability for other modules to manage autoloadable # Adds the ability for other modules to manage autoloadable
# constants. # constants.
#
# @api private
module AutoloadHelper module AutoloadHelper
# Internal: Registers the constants to be auto loaded. # Registers the constants to be auto loaded.
# #
# prefix - The String require prefix. If the path is inside Faraday, then # @param prefix [String] The require prefix. If the path is inside Faraday, then
# it will be prefixed with the root path of this loaded Faraday # it will be prefixed with the root path of this loaded Faraday
# version. # version.
# options - Hash of Symbol => String library names. # @param options [{ Symbol => String }] library names.
# #
# Examples. # @example
# #
# Faraday.autoload_all 'faraday/foo', # Faraday.autoload_all 'faraday/foo',
# :Bar => 'bar' # :Bar => 'bar'
@ -18,7 +20,7 @@ module Faraday
# Faraday::Bar # Faraday::Bar
# #
# #
# Returns nothing. # @return [void]
def autoload_all(prefix, options) def autoload_all(prefix, options)
if prefix =~ /^faraday(\/|$)/i if prefix =~ /^faraday(\/|$)/i
prefix = File.join(Faraday.root_path, prefix) prefix = File.join(Faraday.root_path, prefix)
@ -28,20 +30,20 @@ module Faraday
end end
end end
# Internal: Loads each autoloaded constant. If thread safety is a concern, # Loads each autoloaded constant. If thread safety is a concern,
# wrap this in a Mutex. # wrap this in a Mutex.
# #
# Returns nothing. # @return [void]
def load_autoloaded_constants def load_autoloaded_constants
constants.each do |const| constants.each do |const|
const_get(const) if autoload?(const) const_get(const) if autoload?(const)
end end
end end
# Internal: Filters the module's contents with those that have been already # Filters the module's contents with those that have been already
# autoloaded. # autoloaded.
# #
# Returns an Array of Class/Module objects. # @return [Array<Class, Module>]
def all_loaded_constants def all_loaded_constants
constants.map { |c| const_get(c) }. constants.map { |c| const_get(c) }.
select { |a| a.respond_to?(:loaded?) && a.loaded? } select { |a| a.respond_to?(:loaded?) && a.loaded? }

View File

@ -1,8 +1,8 @@
module Faraday module Faraday
# Public: Connection objects manage the default properties and the middleware # Connection objects manage the default properties and the middleware
# stack for fulfilling an HTTP request. # stack for fulfilling an HTTP request.
# #
# Examples # @example
# #
# conn = Faraday::Connection.new 'http://sushi.com' # conn = Faraday::Connection.new 'http://sushi.com'
# #
@ -14,49 +14,49 @@ module Faraday
# A Set of allowed HTTP verbs. # A Set of allowed HTTP verbs.
METHODS = Set.new [:get, :post, :put, :delete, :head, :patch, :options] METHODS = Set.new [:get, :post, :put, :delete, :head, :patch, :options]
# Public: Returns a Hash of URI query unencoded key/value pairs. # @return [Hash] URI query unencoded key/value pairs.
attr_reader :params attr_reader :params
# Public: Returns a Hash of unencoded HTTP header key/value pairs. # @return [Hash] unencoded HTTP header key/value pairs.
attr_reader :headers attr_reader :headers
# Public: Returns a URI with the prefix used for all requests from this # @return [String] a URI with the prefix used for all requests from this
# Connection. This includes a default host name, scheme, port, and path. # Connection. This includes a default host name, scheme, port, and path.
attr_reader :url_prefix attr_reader :url_prefix
# Public: Returns the Faraday::Builder for this Connection. # @return [Faraday::Builder] Builder for this Connection.
attr_reader :builder attr_reader :builder
# Public: Returns a Hash of the request options. # @return [Hash] request options.
attr_reader :options attr_reader :options
# Public: Returns a Hash of the SSL options. # @return [Hash] SSL options.
attr_reader :ssl attr_reader :ssl
# Public: Returns the parallel manager for this Connection. # @return [Object] the parallel manager for this Connection.
attr_reader :parallel_manager attr_reader :parallel_manager
# Public: Sets the default parallel manager for this connection. # Sets the default parallel manager for this connection.
attr_writer :default_parallel_manager attr_writer :default_parallel_manager
# Public: Gets the Hash proxy options. # @return [Hash] proxy options.
attr_reader :proxy attr_reader :proxy
# Public: Initializes a new Faraday::Connection. # Initializes a new Faraday::Connection.
# #
# url - URI or String base URL to use as a prefix for all # @param url [URI, String] URI or String base URL to use as a prefix for all
# requests (optional). # requests (optional).
# options - Hash or Faraday::ConnectionOptions. # @param options [Hash, Faraday::ConnectionOptions]
# :url - URI or String base URL (default: "http:/"). # @option options [URI, String] :url URI or String base URL (default: "http:/").
# :params - Hash of URI query unencoded key/value pairs. # @option options [Hash<String => String>] :params URI query unencoded key/value pairs.
# :headers - Hash of unencoded HTTP header key/value pairs. # @option options [Hash<String => String>] :headers Hash of unencoded HTTP header key/value pairs.
# :request - Hash of request options. # @option options [Hash] :request Hash of request options.
# :ssl - Hash of SSL options. # @option options [Hash] :ssl Hash of SSL options.
# :proxy - URI, String or Hash of HTTP proxy options # @option options [Hash, URI, String] :proxy proxy options, either as a URL or as a Hash
# (default: "http_proxy" environment variable). # @option options [URI, String] :proxy[:uri]
# :uri - URI or String # @option options [String] :proxy[:user]
# :user - String (optional) # @option options [String] :proxy[:password]
# :password - String (optional) # @yield [self] after all setup has been done
def initialize(url = nil, options = nil) def initialize(url = nil, options = nil)
options = ConnectionOptions.from(options) options = ConnectionOptions.from(options)
@ -91,12 +91,14 @@ module Faraday
@headers[:user_agent] ||= "Faraday v#{VERSION}" @headers[:user_agent] ||= "Faraday v#{VERSION}"
end end
# Public: Sets the Hash of URI query unencoded key/value pairs. # Sets the Hash of URI query unencoded key/value pairs.
# @param hash [Hash]
def params=(hash) def params=(hash)
@params.replace hash @params.replace hash
end end
# Public: Sets the Hash of unencoded HTTP header key/value pairs. # Sets the Hash of unencoded HTTP header key/value pairs.
# @param hash [Hash]
def headers=(hash) def headers=(hash)
@headers.replace hash @headers.replace hash
end end
@ -105,17 +107,17 @@ module Faraday
def_delegators :builder, :build, :use, :request, :response, :adapter, :app def_delegators :builder, :build, :use, :request, :response, :adapter, :app
# Public: Makes an HTTP request without a body. # @!method get(url = nil, params = nil, headers = nil)
# Makes a GET HTTP request without a body.
# @!scope class
# #
# url - The optional String base URL to use as a prefix for all # @param url [String] The optional String base URL to use as a prefix for all
# requests. Can also be the options Hash. # requests. Can also be the options Hash.
# params - Hash of URI query unencoded key/value pairs. # @param params [Hash] Hash of URI query unencoded key/value pairs.
# headers - Hash of unencoded HTTP header key/value pairs. # @param headers [Hash] unencoded HTTP header key/value pairs.
#
# Examples
# #
# @example
# conn.get '/items', {:page => 1}, :accept => 'application/json' # conn.get '/items', {:page => 1}, :accept => 'application/json'
# conn.head '/items/1'
# #
# # ElasticSearch example sending a body with GET. # # ElasticSearch example sending a body with GET.
# conn.get '/twitter/tweet/_search' do |req| # conn.get '/twitter/tweet/_search' do |req|
@ -124,14 +126,40 @@ module Faraday
# req.body = JSON.generate(:query => {...}) # req.body = JSON.generate(:query => {...})
# end # end
# #
# Yields a Faraday::Request for further request customizations. # @yield [Faraday::Request] for further request customizations
# Returns a Faraday::Response. # @return [Faraday::Response]
# @!method head(url = nil, params = nil, headers = nil)
# Makes a HEAD HTTP request without a body.
# @!scope class
# #
# Signature # @param url [String] The optional String base URL to use as a prefix for all
# requests. Can also be the options Hash.
# @param params [Hash] Hash of URI query unencoded key/value pairs.
# @param headers [Hash] unencoded HTTP header key/value pairs.
# #
# <verb>(url = nil, params = nil, headers = nil) # @example
# conn.head '/items/1'
# #
# verb - An HTTP verb: get, head, or delete. # @yield [Faraday::Request] for further request customizations
# @return [Faraday::Response]
# @!method delete(url = nil, params = nil, headers = nil)
# Makes a DELETE HTTP request without a body.
# @!scope class
#
# @param url [String] The optional String base URL to use as a prefix for all
# requests. Can also be the options Hash.
# @param params [Hash] Hash of URI query unencoded key/value pairs.
# @param headers [Hash] unencoded HTTP header key/value pairs.
#
# @example
# conn.delete '/items/1'
#
# @yield [Faraday::Request] for further request customizations
# @return [Faraday::Response]
# @!visibility private
%w[get head delete].each do |method| %w[get head delete].each do |method|
class_eval <<-RUBY, __FILE__, __LINE__ + 1 class_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{method}(url = nil, params = nil, headers = nil) def #{method}(url = nil, params = nil, headers = nil)
@ -142,16 +170,17 @@ module Faraday
end end
RUBY RUBY
end end
# Public: Makes an HTTP request with a body. # @!method post(url = nil, body = nil, headers = nil)
# Makes a POST HTTP request with a body.
# @!scope class
# #
# url - The optional String base URL to use as a prefix for all # @param url [String] The optional String base URL to use as a prefix for all
# requests. Can also be the options Hash. # requests. Can also be the options Hash.
# body - The String body for the request. # @param body [String] body for the request.
# headers - Hash of unencoded HTTP header key/value pairs. # @param headers [Hash] unencoded HTTP header key/value pairs.
#
# Examples
# #
# @example
# conn.post '/items', data, :content_type => 'application/json' # conn.post '/items', data, :content_type => 'application/json'
# #
# # Simple ElasticSearch indexing sample. # # Simple ElasticSearch indexing sample.
@ -161,14 +190,33 @@ module Faraday
# req.body = JSON.generate(:user => 'kimchy', ...) # req.body = JSON.generate(:user => 'kimchy', ...)
# end # end
# #
# Yields a Faraday::Request for further request customizations. # @yield [Faraday::Request] for further request customizations
# Returns a Faraday::Response. # @return [Faraday::Response]
# @!method put(url = nil, body = nil, headers = nil)
# Makes a PUT HTTP request with a body.
# @!scope class
# #
# Signature # @param url [String] The optional String base URL to use as a prefix for all
# requests. Can also be the options Hash.
# @param body [String] body for the request.
# @param headers [Hash] unencoded HTTP header key/value pairs.
# #
# <verb>(url = nil, body = nil, headers = nil) # @example
# # TODO: Make it a PUT example
# conn.post '/items', data, :content_type => 'application/json'
# #
# verb - An HTTP verb: post, put, or patch. # # Simple ElasticSearch indexing sample.
# conn.post '/twitter/tweet' do |req|
# req.headers[:content_type] = 'application/json'
# req.params[:routing] = 'kimchy'
# req.body = JSON.generate(:user => 'kimchy', ...)
# end
#
# @yield [Faraday::Request] for further request customizations
# @return [Faraday::Response]
# @!visibility private
%w[post put patch].each do |method| %w[post put patch].each do |method|
class_eval <<-RUBY, __FILE__, __LINE__ + 1 class_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{method}(url = nil, body = nil, headers = nil, &block) def #{method}(url = nil, body = nil, headers = nil, &block)
@ -177,47 +225,47 @@ module Faraday
RUBY RUBY
end end
# Public: Sets up the Authorization header with these credentials, encoded # Sets up the Authorization header with these credentials, encoded
# with base64. # with base64.
# #
# login - The authentication login. # @param login [String] The authentication login.
# pass - The authentication password. # @param pass [String] The authentication password.
# #
# Examples # @example
# #
# conn.basic_auth 'Aladdin', 'open sesame' # conn.basic_auth 'Aladdin', 'open sesame'
# conn.headers['Authorization'] # conn.headers['Authorization']
# # => "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" # # => "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="
# #
# Returns nothing. # @return [void]
def basic_auth(login, pass) def basic_auth(login, pass)
set_authorization_header(:basic_auth, login, pass) set_authorization_header(:basic_auth, login, pass)
end end
# Public: Sets up the Authorization header with the given token. # Sets up the Authorization header with the given token.
# #
# token - The String token. # @param token [String]
# options - Optional Hash of extra token options. # @param options [Hash] extra token options.
# #
# Examples # @example
# #
# conn.token_auth 'abcdef', :foo => 'bar' # conn.token_auth 'abcdef', :foo => 'bar'
# conn.headers['Authorization'] # conn.headers['Authorization']
# # => "Token token=\"abcdef\", # # => "Token token=\"abcdef\",
# foo=\"bar\"" # foo=\"bar\""
# #
# Returns nothing. # @return [void]
def token_auth(token, options = nil) def token_auth(token, options = nil)
set_authorization_header(:token_auth, token, options) set_authorization_header(:token_auth, token, options)
end end
# Public: Sets up a custom Authorization header. # Sets up a custom Authorization header.
# #
# type - The String authorization type. # @param type [String] authorization type
# token - The String or Hash token. A String value is taken literally, and # @param token [String, Hash] token. A String value is taken literally, and
# a Hash is encoded into comma separated key/value pairs. # a Hash is encoded into comma-separated key/value pairs.
# #
# Examples # @example
# #
# conn.authorization :Bearer, 'mF_9.B5f-4.1JqM' # conn.authorization :Bearer, 'mF_9.B5f-4.1JqM'
# conn.headers['Authorization'] # conn.headers['Authorization']
@ -228,16 +276,17 @@ module Faraday
# # => "Token token=\"abcdef\", # # => "Token token=\"abcdef\",
# foo=\"bar\"" # foo=\"bar\""
# #
# Returns nothing. # @return [void]
def authorization(type, token) def authorization(type, token)
set_authorization_header(:authorization, type, token) set_authorization_header(:authorization, type, token)
end end
# Internal: Check if the adapter is parallel-capable. # Check if the adapter is parallel-capable.
# #
# Yields otherwise or if no adapter is set yet. # @yield if the adapter isn't parallel-capable, or if no adapter is set yet.
# #
# Returns a parallel manager or nil if yielded. # @return [Object, nil] a parallel manager or nil if yielded
# @api private
def default_parallel_manager def default_parallel_manager
@default_parallel_manager ||= begin @default_parallel_manager ||= begin
adapter = @builder.adapter.klass if @builder.adapter adapter = @builder.adapter.klass if @builder.adapter
@ -250,19 +299,19 @@ module Faraday
end end
end end
# Public: Determine if this Faraday::Connection can make parallel requests. # Determine if this Faraday::Connection can make parallel requests.
# #
# Returns true or false. # @return [Boolean]
def in_parallel? def in_parallel?
!!@parallel_manager !!@parallel_manager
end end
# Public: Sets up the parallel manager to make a set of requests. # Sets up the parallel manager to make a set of requests.
# #
# manager - The parallel manager that this Connection's Adapter uses. # @param manager [Object] The parallel manager that this Connection's Adapter uses.
# #
# Yields a block to execute multiple requests. # @yield a block to execute multiple requests.
# Returns nothing. # @return [void]
def in_parallel(manager = nil) def in_parallel(manager = nil)
@parallel_manager = manager || default_parallel_manager { @parallel_manager = manager || default_parallel_manager {
warn "Warning: `in_parallel` called but no parallel-capable adapter on Faraday stack" warn "Warning: `in_parallel` called but no parallel-capable adapter on Faraday stack"
@ -275,7 +324,9 @@ module Faraday
@parallel_manager = nil @parallel_manager = nil
end end
# Public: Sets the Hash proxy options. # Sets the Hash proxy options.
#
# @param new_value [Object]
def proxy=(new_value) def proxy=(new_value)
@manual_proxy = true @manual_proxy = true
@proxy = new_value ? ProxyOptions.from(new_value) : nil @proxy = new_value ? ProxyOptions.from(new_value) : nil
@ -284,13 +335,14 @@ module Faraday
def_delegators :url_prefix, :scheme, :scheme=, :host, :host=, :port, :port= def_delegators :url_prefix, :scheme, :scheme=, :host, :host=, :port, :port=
def_delegator :url_prefix, :path, :path_prefix def_delegator :url_prefix, :path, :path_prefix
# Public: Parses the giving url with URI and stores the individual # Parses the given URL with URI and stores the individual
# components in this connection. These components serve as defaults for # components in this connection. These components serve as defaults for
# requests made by this connection. # requests made by this connection.
# #
# url - A String or URI. # @param url [String, URI]
# @param encoder [Object]
# #
# Examples # @example
# #
# conn = Faraday::Connection.new { ... } # conn = Faraday::Connection.new { ... }
# conn.url_prefix = "https://sushi.com/api" # conn.url_prefix = "https://sushi.com/api"
@ -299,7 +351,7 @@ module Faraday
# #
# conn.get("nigiri?page=2") # accesses https://sushi.com/api/nigiri # conn.get("nigiri?page=2") # accesses https://sushi.com/api/nigiri
# #
# Returns the parsed URI from the given input.. # @return [URI] the parsed URI from the given input
def url_prefix=(url, encoder = nil) def url_prefix=(url, encoder = nil)
uri = @url_prefix = Utils.URI(url) uri = @url_prefix = Utils.URI(url)
self.path_prefix = uri.path self.path_prefix = uri.path
@ -315,12 +367,12 @@ module Faraday
uri uri
end end
# Public: Sets the path prefix and ensures that it always has a leading # Sets the path prefix and ensures that it always has a leading
# slash. # slash.
# #
# value - A String. # @param value [String]
# #
# Returns the new String path prefix. # @return [String] the new path prefix
def path_prefix=(value) def path_prefix=(value)
url_prefix.path = if value url_prefix.path = if value
value = '/' + value unless value[0,1] == '/' value = '/' + value unless value[0,1] == '/'
@ -328,9 +380,13 @@ module Faraday
end end
end end
# Public: Takes a relative url for a request and combines it with the defaults # Takes a relative url for a request and combines it with the defaults
# set on the connection instance. # set on the connection instance.
# #
# @param url [String]
# @param extra_params [Hash]
#
# @example
# conn = Faraday::Connection.new { ... } # conn = Faraday::Connection.new { ... }
# conn.url_prefix = "https://sushi.com/api?token=abc" # conn.url_prefix = "https://sushi.com/api?token=abc"
# conn.scheme # => https # conn.scheme # => https
@ -351,12 +407,12 @@ module Faraday
# Builds and runs the Faraday::Request. # Builds and runs the Faraday::Request.
# #
# method - The Symbol HTTP method. # @param method [Symbol] HTTP method.
# url - The String or URI to access. # @param url [String, URI] String or URI to access.
# body - The request body that will eventually be converted to a string. # @param body [Object] The request body that will eventually be converted to a string.
# headers - Hash of unencoded HTTP header key/value pairs. # @param headers [Hash] unencoded HTTP header key/value pairs.
# #
# Returns a Faraday::Response. # @return [Faraday::Response]
def run_request(method, url, body, headers) def run_request(method, url, body, headers)
if !METHODS.include?(method) if !METHODS.include?(method)
raise ArgumentError, "unknown http method: #{method}" raise ArgumentError, "unknown http method: #{method}"
@ -378,7 +434,10 @@ module Faraday
# Creates and configures the request object. # Creates and configures the request object.
# #
# Returns the new Request. # @param method [Symbol]
#
# @yield [Faraday::Request] if block given
# @return [Faraday::Request]
def build_request(method) def build_request(method)
Request.create(method) do |req| Request.create(method) do |req|
req.params = self.params.dup req.params = self.params.dup
@ -388,13 +447,13 @@ module Faraday
end end
end end
# Internal: Build an absolute URL based on url_prefix. # Build an absolute URL based on url_prefix.
# #
# url - A String or URI-like object # @param url [String, URI]
# params - A Faraday::Utils::ParamsHash to replace the query values # @param params [Faraday::Utils::ParamsHash] A Faraday::Utils::ParamsHash to replace the query values
# of the resulting url (default: nil). # of the resulting url (default: nil).
# #
# Returns the resulting URI instance. # @return [URI]
def build_exclusive_url(url = nil, params = nil, params_encoder = nil) def build_exclusive_url(url = nil, params = nil, params_encoder = nil)
url = nil if url.respond_to?(:empty?) and url.empty? url = nil if url.respond_to?(:empty?) and url.empty?
base = url_prefix base = url_prefix
@ -408,9 +467,11 @@ module Faraday
uri uri
end end
# Internal: Creates a duplicate of this Faraday::Connection. # Creates a duplicate of this Faraday::Connection.
# #
# Returns a Faraday::Connection. # @api private
#
# @return [Faraday::Connection]
def dup def dup
self.class.new(build_exclusive_url, self.class.new(build_exclusive_url,
:headers => headers.dup, :headers => headers.dup,
@ -420,7 +481,14 @@ module Faraday
:request => options.dup) :request => options.dup)
end end
# Internal: Yields username and password extracted from a URI if they both exist. # Yields username and password extracted from a URI if they both exist.
#
# @param uri [URI]
# @yield [username, password] any username and password
# @yieldparam username [String] any username from URI
# @yieldparam password [String] any password from URI
# @return [void]
# @api private
def with_uri_credentials(uri) def with_uri_credentials(uri)
if uri.user and uri.password if uri.user and uri.password
yield(Utils.unescape(uri.user), Utils.unescape(uri.password)) yield(Utils.unescape(uri.user), Utils.unescape(uri.password))

View File

@ -1,6 +1,8 @@
module Faraday module Faraday
# Faraday error base class.
class Error < StandardError; end class Error < StandardError; end
# Faraday client error class.
class ClientError < Error class ClientError < Error
attr_reader :response, :wrapped_exception attr_reader :response, :wrapped_exception

View File

@ -8,7 +8,7 @@ rescue LoadError
end end
module Faraday module Faraday
# Similar but not compatible with ::CompositeReadIO provided by multipart-post. # Similar to, but not compatible with [::CompositeReadIO](https://github.com/nicksieger/multipart-post/blob/master/lib/composite_io.rb) provided by [multipart-post](https://github.com/nicksieger/multipart-post).
class CompositeReadIO class CompositeReadIO
def initialize(*parts) def initialize(*parts)
@parts = parts.flatten @parts = parts.flatten
@ -16,16 +16,23 @@ module Faraday
@index = 0 @index = 0
end end
# @return [Integer] sum of the lengths of all the parts
def length def length
@parts.inject(0) { |sum, part| sum + part.length } @parts.inject(0) { |sum, part| sum + part.length }
end end
# Rewind each of the IOs and reset the index to 0.
#
# @return [void]
def rewind def rewind
@ios.each { |io| io.rewind } @ios.each { |io| io.rewind }
@index = 0 @index = 0
end end
# Read from IOs in order until `length` bytes have been received. # Read from IOs in order until `length` bytes have been received.
#
# @param length [Integer, nil]
# @param outbuf [String, nil]
def read(length = nil, outbuf = nil) def read(length = nil, outbuf = nil)
got_result = false got_result = false
outbuf = outbuf ? outbuf.replace("") : "" outbuf = outbuf ? outbuf.replace("") : ""
@ -43,6 +50,9 @@ module Faraday
(!got_result && length) ? nil : outbuf (!got_result && length) ? nil : outbuf
end end
# Close each of the IOs.
#
# @return [void]
def close def close
@ios.each { |io| io.close } @ios.each { |io| io.close }
end end