Sha256: 66769ed597fac863176e253d75577a59da14cbfd8d325eec6fd086983924e5c7

Contents?: true

Size: 1.93 KB

Versions: 1

Compression:

Stored size: 1.93 KB

Contents

# frozen_string_literal: true

require 'faraday'
require 'faraday/multipart'
require 'faraday/mashify'
require 'vertebrae/response/raise_error'
require 'vertebrae/authorization'

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

    attr_reader :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::Multipart::Middleware
        builder.use Faraday::Request::UrlEncoded
        if configuration.authenticated?
          builder.use Faraday::Request::Authorization, :basic, configuration.username, configuration.password
        end

        builder.use Faraday::Response::Logger if ENV['DEBUG']

        unless options[:raw]
          builder.use Faraday::Mashify::Middleware
          builder.use Faraday::Response::Json
        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

1 entries across 1 versions & 1 rubygems

Version Path
vertebrae-1.0.1 lib/vertebrae/connection.rb