Sha256: d65eef46847d22b780ee096d1a35e9b89bfed560ae35e12d820516852a656b2c

Contents?: true

Size: 1.85 KB

Versions: 3

Compression:

Stored size: 1.85 KB

Contents

require 'faraday'
require 'faraday_middleware'
require 'response/raise_error'
require 'authorization'

module Vertebrae
  class Connection
    include Vertebrae::Constants
    include Vertebrae::Authorization

    attr_accessor :options
    attr_accessor :configuration

    ALLOWED_OPTIONS = [
        :headers,
        :url,
        :params,
        :request,
        :ssl
    ].freeze

    def initialize(options)
      @options = options
      @configuration = Vertebrae::Configuration.new(options)
      @stack = nil
    end

    def options=(options)
      @options = options
      @configuration = Vertebrae::Configuration.new(options)
    end

    # Default middleware stack that uses default adapter as specified at
    # configuration stage.
    #
    def default_middleware
      Proc.new do |builder|
        builder.use Faraday::Request::Multipart
        builder.use Faraday::Request::UrlEncoded
        if configuration.authenticated?
          builder.use Faraday::Request::BasicAuthentication, configuration.username, configuration.password
        end

        builder.use Faraday::Response::Logger if ENV['DEBUG']
        unless options[:raw]
          builder.use FaradayMiddleware::Mashify
          builder.use FaradayMiddleware::ParseJson
        end
        builder.use Vertebrae::Response::RaiseError
        builder.adapter configuration.adapter
      end
    end

    # Exposes middleware builder to facilitate custom stacks and easy
    # addition of new extensions such as cache adapter.
    #
    def stack(&block)
      @stack ||= begin
        if block_given?
          Faraday::RackBuilder.new(&block)
        else
          Faraday::RackBuilder.new(&default_middleware)
        end
      end
    end

    # Returns a Faraday::Connection object
    #
    def connection
      Faraday.new(configuration.faraday_options.merge(:builder => stack))
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
vertebrae-0.6.0 lib/connection.rb
vertebrae-0.5.1 lib/connection.rb
vertebrae-0.5.0 lib/connection.rb