Sha256: 54e8df96a281ca53809c9a165d25c467935764339c2e05a4fc5f090c7ca025db

Contents?: true

Size: 1.69 KB

Versions: 6

Compression:

Stored size: 1.69 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
    SQL_DATETIME_WITH_NSEC = "%Y-%m-%d %H:%M:%S.%N"

    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|
        attribute_name = column.to_s.split(".").last
        column_value(record, attribute_name)
      end
      return positions.first if positions.size == 1
      positions
    end

    def finder_cursor
      JobIteration::ActiveRecordCursor.new(@relation, @columns, @cursor)
    end

    def column_value(record, attribute)
      value = record.read_attribute(attribute.to_sym)
      case record.class.columns_hash.fetch(attribute).type
      when :datetime
        value.strftime(SQL_DATETIME_WITH_NSEC)
      else
        value
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
job-iteration-1.2.0 lib/job-iteration/active_record_enumerator.rb
job-iteration-1.1.14 lib/job-iteration/active_record_enumerator.rb
job-iteration-1.1.13 lib/job-iteration/active_record_enumerator.rb
job-iteration-1.1.12 lib/job-iteration/active_record_enumerator.rb
job-iteration-1.1.11 lib/job-iteration/active_record_enumerator.rb
job-iteration-1.1.10 lib/job-iteration/active_record_enumerator.rb