Class: Faraday::Connection

### Home Classes Methods

### In Files

- lib/faraday/connection.rb

### Parent

Object

### Methods

- ::new
- #authorization
- #basic_auth
- #build_exclusive_url
- #build_request
- #build_url
- #default_parallel_manager
- #dup
- #headers=
- #in_parallel
- #in_parallel?
- #params=
- #path_prefix=
- #proxy
- #run_request
- #set_authorization_header
- #token_auth
- #url_prefix=
- #with_uri_credentials

### Class/Module Index

Quicksearch

- Faraday
- Faraday::Adapter
- Faraday::Adapter::EMHttp
- Faraday::Adapter::EMHttp::Manager
- Faraday::Adapter::EMHttp::Options
- Faraday::Adapter::EMSynchrony
- Faraday::Adapter::EMSynchrony::ParallelManager
- Faraday::Adapter::Excon
- Faraday::Adapter::HTTPClient
- Faraday::Adapter::NetHttp
- Faraday::Adapter::NetHttpPersistent
- Faraday::Adapter::Parallelism
- Faraday::Adapter::Patron
- Faraday::Adapter::Rack
- Faraday::Adapter::Test
- Faraday::Adapter::Test::Stub
- Faraday::Adapter::Test::Stubs
- Faraday::Adapter::Test::Stubs::NotFound
- Faraday::Adapter::Typhoeus
- Faraday::AutoloadHelper
- Faraday::ClientError
- Faraday::CompositeReadIO
- Faraday::Connection
- Faraday::ConnectionFailed
- Faraday::ConnectionOptions
- Faraday::Env
- Faraday::Error
- Faraday::FlatParamsEncoder
- Faraday::Middleware
- Faraday::MiddlewareRegistry
- Faraday::MissingDependency
- Faraday::NestedParamsEncoder
- Faraday::Options
- Faraday::ParsingError
- Faraday::ProxyOptions
- Faraday::RackBuilder
- Faraday::RackBuilder::Handler
- Faraday::RackBuilder::StackLocked
- Faraday::Request
- Faraday::Request::Authorization
- Faraday::Request::BasicAuthentication
- Faraday::Request::Instrumentation
- Faraday::Request::Instrumentation::Options
- Faraday::Request::Multipart
- Faraday::Request::Retry
- Faraday::Request::Retry::Options
- Faraday::Request::TokenAuthentication
- Faraday::Request::UrlEncoded
- Faraday::RequestOptions
- Faraday::ResourceNotFound
- Faraday::Response
- Faraday::Response::Logger
- Faraday::Response::Middleware
- Faraday::Response::RaiseError
- Faraday::SSLError
- Faraday::SSLOptions
- Faraday::TimeoutError
- Faraday::Utils
- Faraday::Utils::Headers
- Faraday::Utils::ParamsHash
- EmHttpSslPatch
- Object

No matching classes.

# Faraday::Connection

Public: Connection objects manage the default properties and the middleware stack for fulfilling an HTTP request.

Examples

    conn = Faraday::Connection.new 'http://sushi.com'

    # GET http://sushi.com/nigiri
    conn.get 'nigiri'
    # => #<Faraday::Response>

### Constants

METHODS

  A Set of allowed HTTP verbs.

### Attributes

builder[R]

Public: Returns the Faraday::Builder for this Connection.

default_parallel_manager[W]

Public: Sets the default parallel manager for this connection.

headers[R]

Public: Returns a Hash of unencoded HTTP header key/value pairs.

options[R]

Public: Returns a Hash of the request options.

parallel_manager[R]

Public: Returns the parallel manager for this Connection.

params[R]

Public: Returns a Hash of URI query unencoded key/value pairs.

ssl[R]

Public: Returns a Hash of the SSL options.

url_prefix[R]

Public: Returns a URI with the prefix used for all requests from this Connection. This includes a default host name, scheme, port, and path.

### Public Class Methods

new(url = nil, options = nil) click to toggle source

Public: Initializes a new Faraday::Connection.

url - URI or String base URL to use as a prefix for all

    requests (optional).

options - Hash or Faraday::ConnectionOptions.

    :url     - URI or String base URL (default: "http:/").
    :params  - Hash of URI query unencoded key/value pairs.
    :headers - Hash of unencoded HTTP header key/value pairs.
    :request - Hash of request options.
    :ssl     - Hash of SSL options.
    :proxy   - URI, String or Hash of HTTP proxy options
              (default: "http_proxy" environment variable).
              :uri      - URI or String
              :user     - String (optional)
              :password - String (optional)

    # File lib/faraday/connection.rb, line 57
    def initialize(url = nil, options = nil)
      if url.is_a?(Hash)
        options = ConnectionOptions.from(url)
        url     = options.url
      else
        options = ConnectionOptions.from(options)
      end

      @parallel_manager = nil
      @headers = Utils::Headers.new
      @params  = Utils::ParamsHash.new
      @options = options.request
      @ssl = options.ssl
      @default_parallel_manager = options.parallel_manager

      @builder = options.builder || begin
        # pass an empty block to Builder so it doesn't assume default middleware
        options.new_builder(block_given? ? Proc.new { |b| } : nil)
      end

      self.url_prefix = url || 'http:/'

      @params.update(options.params)   if options.params
      @headers.update(options.headers) if options.headers

      @proxy = nil
      proxy(options.fetch(:proxy) {
        uri = ENV['http_proxy']
        if uri && !uri.empty?
          uri = 'http://' + uri if uri !~ /^http/
          uri
        end
      })

      yield(self) if block_given?

      @headers[:user_agent] ||= "Faraday v#{VERSION}"
    end

### Public Instance Methods

authorization(type, token) click to toggle source

Public: Sets up a custom Authorization header.

type - The String authorization type. token - The String or Hash token. A String value is taken literally, and

    a Hash is encoded into comma separated key/value pairs.

Examples

    conn.authorization :Bearer, 'mF_9.B5f-4.1JqM'
    conn.headers['Authorization']
    # => "Bearer mF_9.B5f-4.1JqM"

    conn.authorization :Token, :token => 'abcdef', :foo => 'bar'
    conn.headers['Authorization']
    # => "Token token=\"abcdef\",
                foo=\"bar\""

Returns nothing.

    # File lib/faraday/connection.rb, line 234
    def authorization(type, token)
      set_authorization_header(:authorization, type, token)
    end

basic_auth(login, pass) click to toggle source

Public: Sets up the Authorization header with these credentials, encoded with base64.

login - The authentication login. pass - The authentication password.

Examples

    conn.basic_auth 'Aladdin', 'open sesame'
    conn.headers['Authorization']
    # => "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="

Returns nothing.

    # File lib/faraday/connection.rb, line 195
    def basic_auth(login, pass)
      set_authorization_header(:basic_auth, login, pass)
    end

build_exclusive_url(url = nil, params = nil) click to toggle source

Internal: Build an absolute URL based on url_prefix.

url - A String or URI-like object params - A Faraday::Utils::ParamsHash to replace the query values

    of the resulting url (default: nil).

Returns the resulting URI instance.

    # File lib/faraday/connection.rb, line 399
    def build_exclusive_url(url = nil, params = nil)
      url = nil if url.respond_to?(:empty?) and url.empty?
      base = url_prefix
      if url and base.path and base.path !~ /\/$/
        base = base.dup
        base.path = base.path + '/'  # ensure trailing slash
      end
      uri = url ? base + url : base
      uri.query = params.to_query(options.params_encoder) if params
      uri.query = nil if uri.query and uri.query.empty?
      uri
    end

build_request(method) click to toggle source

Creates and configures the request object.

Returns the new Request.

    # File lib/faraday/connection.rb, line 383
    def build_request(method)
      Request.create(method) do |req|
        req.params  = self.params.dup
        req.headers = self.headers.dup
        req.options = self.options.merge(:proxy => self.proxy)
        yield(req) if block_given?
      end
    end

build_url(url = nil, extra_params = nil) click to toggle source

Public: Takes a relative url for a request and combines it with the defaults set on the connection instance.

    conn = Faraday::Connection.new { ... }
    conn.url_prefix = "https://sushi.com/api?token=abc"
    conn.scheme      # => https
    conn.path_prefix # => "/api"

    conn.build_url("nigiri?page=2")      # => https://sushi.com/api/nigiri?token=abc&page=2
    conn.build_url("nigiri", :page => 2) # => https://sushi.com/api/nigiri?token=abc&page=2

    # File lib/faraday/connection.rb, line 347
    def build_url(url = nil, extra_params = nil)
      uri = build_exclusive_url(url)

      query_values = params.dup.merge_query(uri.query, options.params_encoder)
      query_values.update extra_params if extra_params
      uri.query = query_values.empty? ? nil : query_values.to_query(options.params_encoder)

      uri
    end

default_parallel_manager() click to toggle source

Internal: Traverse the middleware stack in search of a parallel-capable adapter.

Yields in case of not found.

Returns a parallel manager or nil if not found.

    # File lib/faraday/connection.rb, line 244
    def default_parallel_manager
      @default_parallel_manager ||= begin
        handler = @builder.handlers.detect do |h|
          h.klass.respond_to?(:supports_parallel?) and h.klass.supports_parallel?
        end

        if handler
          handler.klass.setup_parallel_manager
        elsif block_given?
          yield
        end
      end
    end

dup() click to toggle source

Internal: Creates a duplicate of this Faraday::Connection.

Returns a Faraday::Connection.

    # File lib/faraday/connection.rb, line 415
    def dup
      self.class.new(build_exclusive_url, :headers => headers.dup, :params => params.dup, :builder => builder.dup, :ssl => ssl.dup)
    end

headers=(hash) click to toggle source

Public: Sets the Hash of unencoded HTTP header key/value pairs.

    # File lib/faraday/connection.rb, line 102
    def headers=(hash)
      @headers.replace hash
    end

in_parallel(manager = nil) click to toggle source

Public: Sets up the parallel manager to make a set of requests.

manager - The parallel manager that this Connection's Adapter uses.

Yields a block to execute multiple requests. Returns nothing.

    # File lib/faraday/connection.rb, line 271
    def in_parallel(manager = nil)
      @parallel_manager = manager || default_parallel_manager {
        warn "Warning: `in_parallel` called but no parallel-capable adapter on Faraday stack"
        warn caller[2,10].join("\n")
        nil
      }
      yield
      @parallel_manager && @parallel_manager.run
    ensure
      @parallel_manager = nil
    end

in_parallel?() click to toggle source

Public: Determine if this Faraday::Connection can make parallel requests.

Returns true or false.

    # File lib/faraday/connection.rb, line 261
    def in_parallel?
      !!@parallel_manager
    end

params=(hash) click to toggle source

Public: Sets the Hash of URI query unencoded key/value pairs.

    # File lib/faraday/connection.rb, line 97
    def params=(hash)
      @params.replace hash
    end

path_prefix=(value) click to toggle source

Public: Sets the path prefix and ensures that it always has a leading slash.

value - A String.

Returns the new String path prefix.

    # File lib/faraday/connection.rb, line 329
    def path_prefix=(value)
      url_prefix.path = if value
        value = '/' + value unless value[0,1] == '/'
        value
      end
    end

proxy(arg = nil) click to toggle source

Public: Gets or Sets the Hash proxy options.

    # File lib/faraday/connection.rb, line 284
    def proxy(arg = nil)
      return @proxy if arg.nil?
      @proxy = ProxyOptions.from(arg)
    end

run_request(method, url, body, headers) click to toggle source

Builds and runs the Faraday::Request.

method - The Symbol HTTP method. url - The String or URI to access. body - The String body headers - Hash of unencoded HTTP header key/value pairs.

Returns a Faraday::Response.

    # File lib/faraday/connection.rb, line 365
    def run_request(method, url, body, headers)
      if !METHODS.include?(method)
        raise ArgumentError, "unknown http method: #{method}"
      end

      request = build_request(method) do |req|
        req.url(url)                if url
        req.headers.update(headers) if headers
        req.body = body             if body
        yield(req) if block_given?
      end

      builder.build_response(self, request)
    end

set_authorization_header(header_type, *args) click to toggle source

    # File lib/faraday/connection.rb, line 426
    def set_authorization_header(header_type, *args)
      header = Faraday::Request.lookup_middleware(header_type).
        header(*args)
      headers[Faraday::Request::Authorization::KEY] = header
    end

token_auth(token, options = nil) click to toggle source

Public: Sets up the Authorization header with the given token.

token - The String token. options - Optional Hash of extra token options.

Examples

    conn.token_auth 'abcdef', :foo => 'bar'
    conn.headers['Authorization']
    # => "Token token=\"abcdef\",
                foo=\"bar\""

Returns nothing.

    # File lib/faraday/connection.rb, line 212
    def token_auth(token, options = nil)
      set_authorization_header(:token_auth, token, options)
    end

url_prefix=(url, encoder = nil) click to toggle source

Public: Parses the giving url with URI and stores the individual components in this connection. These components serve as defaults for requests made by this connection.

url - A String or URI.

Examples

    conn = Faraday::Connection.new { ... }
    conn.url_prefix = "https://sushi.com/api"
    conn.scheme      # => https
    conn.path_prefix # => "/api"

    conn.get("nigiri?page=2") # accesses https://sushi.com/api/nigiri

Returns the parsed URI from teh given input..

    # File lib/faraday/connection.rb, line 308
    def url_prefix=(url, encoder = nil)
      uri = @url_prefix = Utils.URI(url)
      self.path_prefix = uri.path

      params.merge_query(uri.query, encoder)
      uri.query = nil

      with_uri_credentials(uri) do |user, password|
        basic_auth user, password
        uri.user = uri.password = nil
      end

      uri
    end

with_uri_credentials(uri) click to toggle source

Internal: Yields username and password extracted from a URI if they both exist.

    # File lib/faraday/connection.rb, line 420
    def with_uri_credentials(uri)
      if uri.user and uri.password
        yield(Utils.unescape(uri.user), Utils.unescape(uri.password))
      end
    end

[Validate]

Generated with the Darkfish Rdoc Generator 2.