Class: JobIteration::ActiveRecordEnumerator

Inherits:
Object
  • Object
show all
Defined in:
lib/job-iteration/active_record_enumerator.rb

Overview

Builds Enumerator based on ActiveRecord Relation. Supports enumerating on rows and batches.

See Also:

Constant Summary collapse

SQL_DATETIME_WITH_NSEC =
"%Y-%m-%d %H:%M:%S.%N"

Instance Method Summary collapse

Constructor Details

#initialize(relation, columns: nil, batch_size: 100, timezone: nil, cursor: nil) ⇒ ActiveRecordEnumerator

Returns a new instance of ActiveRecordEnumerator.



10
11
12
13
14
15
16
17
18
19
20
# File 'lib/job-iteration/active_record_enumerator.rb', line 10

def initialize(relation, columns: nil, batch_size: 100, timezone: nil, cursor: nil)
  @relation = relation
  @batch_size = batch_size
  @timezone = timezone
  @columns = if columns
    Array(columns)
  else
    Array(relation.primary_key).map { |pk| "#{relation.table_name}.#{pk}" }
  end
  @cursor = cursor
end

Instance Method Details

#batchesObject



32
33
34
35
36
37
38
39
# File 'lib/job-iteration/active_record_enumerator.rb', line 32

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

#recordsObject



22
23
24
25
26
27
28
29
30
# File 'lib/job-iteration/active_record_enumerator.rb', line 22

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

#sizeObject



41
42
43
# File 'lib/job-iteration/active_record_enumerator.rb', line 41

def size
  @relation.count(:all)
end