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, instance: nil, instances: 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, instance: nil, instances: nil) ⇒ ActiveRecordEnumerator
Returns a new instance of ActiveRecordEnumerator.
10 11 12 13 14 15 16 17 18 19 20 21 22 |
# File 'lib/job-iteration/active_record_enumerator.rb', line 10 def initialize(relation, columns: nil, batch_size: 100, timezone: nil, cursor: nil, instance: nil, instances: 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 @instance = instance @instances = instances end |
Instance Method Details
#batches ⇒ Object
34 35 36 37 38 39 40 41 |
# File 'lib/job-iteration/active_record_enumerator.rb', line 34 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
24 25 26 27 28 29 30 31 32 |
# File 'lib/job-iteration/active_record_enumerator.rb', line 24 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
43 44 45 46 |
# File 'lib/job-iteration/active_record_enumerator.rb', line 43 def size full_size = @relation.count(:all) @instances.present? ? full_size / @instances : full_size end |