Class: JobIteration::ActiveRecordEnumerator
- Inherits:
-
Object
- Object
- JobIteration::ActiveRecordEnumerator
- Defined in:
- lib/job-iteration/active_record_enumerator.rb
Overview
Builds Enumerator based on ActiveRecord Relation. Supports enumerating on rows and batches.
Constant Summary collapse
- SQL_DATETIME_WITH_NSEC =
"%Y-%m-%d %H:%M:%S.%N"
Instance Method Summary collapse
- #batches ⇒ Object
-
#initialize(relation, columns: nil, batch_size: 100, timezone: nil, cursor: nil) ⇒ ActiveRecordEnumerator
constructor
A new instance of ActiveRecordEnumerator.
- #records ⇒ Object
- #size ⇒ Object
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
#batches ⇒ Object
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 = instrument_next_batch(cursor)) yielder.yield(records, cursor_value(records.last)) if records.any? end end end |
#records ⇒ Object
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 |
#size ⇒ Object
41 42 43 |
# File 'lib/job-iteration/active_record_enumerator.rb', line 41 def size @relation.count(:all) end |