class MongoBatch::Batcher

Attributes

batch_size[R]
offset[R]
order_by[R]
query[R]
to[R]

Public Class Methods

new(query, options = {}) click to toggle source
# File lib/mongo_batch.rb, line 5
def initialize(query, options = {})
  @query = query
  @batch_size = options.fetch(:batch_size) { 1_000 }
  @to = options.fetch(:to) { query.count }
  @offset = options.fetch(:offset) { 0 }
  @order_by = options.fetch(:order_by) { { _id: :asc } }
end

Public Instance Methods

batches() click to toggle source
# File lib/mongo_batch.rb, line 13
def batches
  Enumerator.new(to) do |yielder|
    processed_so_far = offset

    offset.step(by: batch_size, to: to - batch_size).each do |offset|
      yielder << with_order.limit(batch_size).skip(offset)
      processed_so_far += batch_size
    end

    if processed_so_far < to
      last_limit = to - processed_so_far
      yielder << with_order.limit(last_limit).skip(processed_so_far)
    end
  end
end
options() click to toggle source
# File lib/mongo_batch.rb, line 33
def options
  query.criteria.options
end
with_order() click to toggle source
# File lib/mongo_batch.rb, line 29
def with_order
  options.sort ? query : query.order_by(order_by)
end