Sha256: e855dd6a9af321d015f61b5af3750082023358b3339557041851a8bc1f327402

Contents?: true

Size: 1.41 KB

Versions: 5

Compression:

Stored size: 1.41 KB

Contents

# frozen_string_literal: true

require 'net/http'
require_relative '../options'

class Valvat
  class Lookup
    class Base
      def initialize(vat, options = {})
        @vat = Valvat(vat)
        @options = Valvat::Options(options)
        @requester = @options[:requester] && Valvat(@options[:requester])
      end

      def perform
        response = fetch(endpoint_uri)

        case response
        when Net::HTTPSuccess
          parse(response.body)
        else
          { error: Valvat::HTTPError.new(response.code, self.class) }
        end
      end

      private

      def endpoint_uri
        raise NotImplementedError
      end

      def build_request(uri)
        raise NotImplementedError
      end

      def parse(body)
        raise NotImplementedError
      end

      def fetch(uri, limit = 0)
        response = send_request(uri)

        if response == Net::HTTPRedirection && limit < 5
          fetch(URI.parse(response['Location']), limit + 1)
        else
          response
        end
      rescue Errno::ECONNRESET, IOError
        raise if limit > 5

        fetch(uri, limit + 1)
      end

      def send_request(uri)
        request = build_request(uri)

        Net::HTTP.start(uri.host, uri.port, options_for(uri)) do |http|
          http.request(request)
        end
      end

      def options_for(uri)
        @options[:http].merge({ use_ssl: URI::HTTPS === uri })
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
valvat-1.4.4 lib/valvat/lookup/base.rb
valvat-1.4.3 lib/valvat/lookup/base.rb
valvat-1.4.2 lib/valvat/lookup/base.rb
valvat-1.4.1 lib/valvat/lookup/base.rb
valvat-1.4.0 lib/valvat/lookup/base.rb