Module: BetterRecord::Batches

Defined in:
lib/better_record/batches.rb

Instance Method Summary collapse

Instance Method Details

#split_batches(options = {}, &block) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/better_record/batches.rb', line 6

def split_batches(options = {}, &block)
  options.assert_valid_keys(:start, :batch_size, :preserve_order)
  if block_given? && arel.orders.present? && options[:preserve_order]
    relation = self
    offset = options[:start] || 0
    batch_size = options[:batch_size] || 1000

    total = relation.count(:*)
    records = relation.limit(batch_size).offset(offset).to_a
    while records.any?
      records_size = records.size

      block.call records

      break if records_size < batch_size
      offset += batch_size
      records = relation.limit(batch_size).offset(offset).to_a
    end
    nil
  else
    find_in_batches(options.except(:preserve_order), &block)
  end
end

#split_batches_values(**options) ⇒ Object



30
31
32
33
34
35
36
# File 'lib/better_record/batches.rb', line 30

def split_batches_values(**options)
  split_batches options do |b|
    b.each do |v|
      yield v
    end
  end
end