123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- module ActiveRecord
- module AsBatches
- class Batch
- def initialize(arel, args)
- @offset = arel.offset || 0
- @limit = arel.limit
- @size = args[:size] || 100
- return if !@limit || (@limit > @size)
- @size = @limit
- end
- def get_records(query)
- query.offset(@offset).limit(@size).all
- end
- def as_batches(query, &)
- records = get_records(query)
- while records.any?
- @offset += records.size
- records.each(&)
- if @limit
- @limit -= records.size
- if @limit < size
- @size = @limit
- end
- return if @limit.zero?
- end
- records = get_records(query)
- end
- end
- end
- def as_batches(args = {}, &)
- Batch.new(arel, args).as_batches(self, &)
- end
- end
- class Relation
- include AsBatches
- end
- end
|