Sha256: 6d93943b4cdf5f3d7ac465ad73a6caf39d97cb5cbf90ed001d12a99179087c97

Contents?: true

Size: 1.52 KB

Versions: 3

Compression:

Stored size: 1.52 KB

Contents

require 'grocer'
require 'grocer/no_gateway_error'
require 'grocer/no_port_error'
require 'grocer/ssl_connection'

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

    def initialize(options = {})
      @certificate = options.fetch(:certificate) { nil }
      @gateway = options.fetch(:gateway) { fail NoGatewayError }
      @port = options.fetch(:port) { fail NoPortError }
      @passphrase = options.fetch(:passphrase) { nil }
      @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
        ssl.connect unless ssl.connected?
        yield
      rescue StandardError, Errno::EPIPE
        raise unless attempts < @retries

        destroy_connection
        attempts += 1
        retry
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
grocer-0.0.11 lib/grocer/connection.rb
grocer-0.0.10 lib/grocer/connection.rb
grocer-0.0.9 lib/grocer/connection.rb