Module: BetterRecord::Batches

Defined in:
lib/better_record/batches.rb

Instance Method Summary collapse

Instance Method Details

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



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

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