Class: JobIteration::ActiveRecordBatchEnumerator

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/job-iteration/active_record_batch_enumerator.rb,
lib/job-iteration/active_record_batch_enumerator/column_manager.rb

Overview

Builds Batch Enumerator based on ActiveRecord Relation.

See Also:

Defined Under Namespace

Classes: ColumnManager

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) ⇒ ActiveRecordBatchEnumerator

Returns a new instance of ActiveRecordBatchEnumerator.



13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/job-iteration/active_record_batch_enumerator.rb', line 13

def initialize(relation, columns: nil, batch_size: 100, timezone: nil, cursor: nil)
  @batch_size = batch_size
  @timezone = timezone
  @column_mgr = ColumnManager.new(relation: relation, columns: columns)
  @cursor = Array.wrap(cursor)
  @initial_cursor = @cursor

  if relation.arel.orders.present? || relation.arel.taken.present?
    raise JobIteration::ActiveRecordCursor::ConditionNotSupportedError
  end

  @base_relation = relation.reorder(@column_mgr.columns.join(","))
end

Instance Method Details

#eachObject



27
28
29
30
31
32
33
# File 'lib/job-iteration/active_record_batch_enumerator.rb', line 27

def each
  return to_enum { size } unless block_given?

  while (relation = next_batch)
    yield relation, cursor_value
  end
end

#sizeObject



35
36
37
# File 'lib/job-iteration/active_record_batch_enumerator.rb', line 35

def size
  (@base_relation.count(:all) + @batch_size - 1) / @batch_size # ceiling division
end