arkency/rails_event_store

View on GitHub
ruby_event_store-active_record/lib/ruby_event_store/active_record/batch_enumerator.rb

Summary

Maintainability
A
35 mins
Test Coverage
# frozen_string_literal: true

module RubyEventStore
  module ActiveRecord
    class BatchEnumerator
      def initialize(batch_size, total_limit, reader)
        @batch_size = batch_size
        @total_limit = total_limit
        @reader = reader
      end

      def each
        return to_enum unless block_given?
        offset_id = nil

        0.step(total_limit - 1, batch_size) do |batch_offset|
          batch_limit = [batch_size, total_limit - batch_offset].min
          results, offset_id = reader.call(offset_id, batch_limit)

          yield results if results.any?
          break if results.size < batch_size
        end
      end

      def first
        each.first
      end

      def to_a
        each.to_a
      end

      private

      attr_reader :batch_size, :total_limit, :reader
    end
  end
end