Sha256: 998a8e70cace77abed78ac576c4940ff6dda7b39868204846baa7eea5e11cc5b
Contents?: true
Size: 1.44 KB
Versions: 8
Compression:
Stored size: 1.44 KB
Contents
# frozen_string_literal: true require_relative "./active_record_cursor" module JobIteration # Builds Enumerator based on ActiveRecord Relation. Supports enumerating on rows and batches. # @see EnumeratorBuilder class ActiveRecordEnumerator def initialize(relation, columns: nil, batch_size: 100, cursor: nil) @relation = relation @batch_size = batch_size @columns = Array(columns || "#{relation.table_name}.#{relation.primary_key}") @cursor = cursor end def records Enumerator.new(method(:size)) do |yielder| batches.each do |batch, _| batch.each do |record| yielder.yield(record, cursor_value(record)) end end end end def batches cursor = finder_cursor Enumerator.new(method(:size)) do |yielder| while records = cursor.next_batch(@batch_size) yielder.yield(records, cursor_value(records.last)) if records.any? end end end def size @relation.count end private def cursor_value(record) positions = @columns.map do |column| method = column.to_s.split('.').last attribute = record.read_attribute(method.to_sym) attribute.is_a?(Time) ? attribute.to_s(:db) : attribute end return positions.first if positions.size == 1 positions end def finder_cursor JobIteration::ActiveRecordCursor.new(@relation, @columns, @cursor) end end end
Version data entries
8 entries across 8 versions & 1 rubygems