Method: EachBatch::BatchEnumerator#initialize

Defined in:
lib/each_batch/batch_enumerator.rb

#initialize(relation, of: DEFAULT_BATCH_SIZE, load: false, order: :asc, keys: nil) ⇒ BatchEnumerator

Returns a new instance of BatchEnumerator.

Raises:

  • (ArgumentError)


13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/each_batch/batch_enumerator.rb', line 13

def initialize(relation, of: DEFAULT_BATCH_SIZE, load: false, order: :asc, keys: nil)
  raise ArgumentError, 'Batch size must be a positive integer' if of != of.to_i || of <= 0 
  
  order = order.to_s
  raise ArgumentError, 'Invalid order' if !order.casecmp('desc').zero? && !order.casecmp('asc').zero?
  
  pk_name = relation.primary_key.to_s
  keys = keys&.map(&:to_s) || [pk_name.to_s]

  # TODO: This is for safety, since there is no easy way to determine whether the order
  # is deterministic or not. PK guarantees that.
  raise ArgumentError, 'Primary key must be that last key' if keys.last != pk_name

  if relation.select_values.present? && (relation.select_values.map(&:to_s) & keys).to_set != keys.to_set
    raise ArgumentError, 'Not all keys are included in the custom select clause'
  end

  @relation = relation
  @of = of
  @load = load
  @order = order
  @keys = keys
end