Sha256: a0461a00588779ee1445f3b5374b09ee5e913056b6e15589d72a2cc71ec8a17c

Contents?: true

Size: 1.22 KB

Versions: 14

Compression:

Stored size: 1.22 KB

Contents

# frozen_string_literal: true

module ConvenientService
  module Support
    module FiniteLoop
      MAX_ITERATION_COUNT = 1_000

      module Errors
        class MaxIterationCountExceeded < ::StandardError
          def initialize(limit:)
            message = <<~TEXT
              Max iteration count is exceeded. Current limit is #{limit}.

              Consider using `max_iteration_count` or `raise_on_exceedance` options if that is not the expected behavior.
            TEXT

            super(message)
          end
        end

        class NoBlockGiven < ::StandardError
          def initialize
            message = <<~TEXT
              `finite_loop` always expects a block to be given.
            TEXT

            super(message)
          end
        end
      end

      private

      def finite_loop(max_iteration_count: MAX_ITERATION_COUNT, raise_on_exceedance: true, &block)
        raise Errors::NoBlockGiven.new unless block

        loop.with_index do |_, index|
          if index >= max_iteration_count
            break unless raise_on_exceedance

            raise Errors::MaxIterationCountExceeded.new(limit: max_iteration_count)
          end

          block.call(index)
        end
      end
    end
  end
end

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
convenient_service-0.11.0 lib/convenient_service/support/finite_loop.rb
convenient_service-0.10.1 lib/convenient_service/support/finite_loop.rb
convenient_service-0.10.0 lib/convenient_service/support/finite_loop.rb
convenient_service-0.9.0 lib/convenient_service/support/finite_loop.rb
convenient_service-0.8.0 lib/convenient_service/support/finite_loop.rb
convenient_service-0.7.0 lib/convenient_service/support/finite_loop.rb
convenient_service-0.6.0 lib/convenient_service/support/finite_loop.rb
convenient_service-0.5.0 lib/convenient_service/support/finite_loop.rb
convenient_service-0.4.0 lib/convenient_service/support/finite_loop.rb
convenient_service-0.3.1 lib/convenient_service/support/finite_loop.rb
convenient_service-0.3.0 lib/convenient_service/support/finite_loop.rb
convenient_service-0.2.1 lib/convenient_service/support/finite_loop.rb
convenient_service-0.2.0 lib/convenient_service/support/finite_loop.rb
convenient_service-0.1.0 lib/convenient_service/support/finite_loop.rb