Sha256: cf4dd3e2aaf49eb16fb8395090f4ab500d36af824577883d04a57323327ffdd8

Contents?: true

Size: 1.56 KB

Versions: 10

Compression:

Stored size: 1.56 KB

Contents

require 'grocer'
require 'grocer/ssl_connection'

module Grocer
  class Connection
    attr_reader :certificate, :passphrase, :gateway, :port, :retries

    def initialize(options = {})
      @certificate = options.fetch(:certificate) { nil }
      @passphrase = options.fetch(:passphrase) { nil }
      @gateway = options.fetch(:gateway) { fail NoGatewayError }
      @port = options.fetch(:port) { fail NoPortError }
      @retries = options.fetch(:retries) { 3 }
    end

    def read(size = nil, buf = nil)
      with_connection do
        ssl.read(size, buf)
      end
    end

    def write(content)
      with_connection do
        ssl.write(content)
      end
    end

    def connect
      ssl.connect unless ssl.connected?
    end

    private

    def ssl
      @ssl_connection ||= build_connection
    end

    def build_connection
      Grocer::SSLConnection.new(certificate: certificate,
                                passphrase: passphrase,
                                gateway: gateway,
                                port: port)
    end

    def destroy_connection
      return unless @ssl_connection

      @ssl_connection.disconnect rescue nil
      @ssl_connection = nil
    end

    def with_connection
      attempts = 1
      begin
        connect
        yield
      rescue => e
        if e.class == OpenSSL::SSL::SSLError && e.message =~ /certificate expired/i
          e.extend(CertificateExpiredError)
          raise
        end

        raise unless attempts < retries

        destroy_connection
        attempts += 1
        retry
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
grocer-0.7.1 lib/grocer/connection.rb
grocer-0.7.0 lib/grocer/connection.rb
grocer-0.6.1 lib/grocer/connection.rb
grocer-0.6.0 lib/grocer/connection.rb
grocer-0.5.0 lib/grocer/connection.rb
grocer-0.4.1 lib/grocer/connection.rb
grocer-0.4.0 lib/grocer/connection.rb
grocer-0.3.4 lib/grocer/connection.rb
grocer-0.3.3 lib/grocer/connection.rb
grocer-0.3.2 lib/grocer/connection.rb