Class: MongoBatch::Batcher

Inherits:
Object
  • Object
show all
Defined in:
lib/mongo_batch.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(query, options = {}) ⇒ Batcher

Returns a new instance of Batcher.



5
6
7
8
9
10
11
# 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

Instance Attribute Details

#batch_sizeObject (readonly)

Returns the value of attribute batch_size.



3
4
5
# File 'lib/mongo_batch.rb', line 3

def batch_size
  @batch_size
end

#offsetObject (readonly)

Returns the value of attribute offset.



3
4
5
# File 'lib/mongo_batch.rb', line 3

def offset
  @offset
end

#order_byObject (readonly)

Returns the value of attribute order_by.



3
4
5
# File 'lib/mongo_batch.rb', line 3

def order_by
  @order_by
end

#queryObject (readonly)

Returns the value of attribute query.



3
4
5
# File 'lib/mongo_batch.rb', line 3

def query
  @query
end

#toObject (readonly)

Returns the value of attribute to.



3
4
5
# File 'lib/mongo_batch.rb', line 3

def to
  @to
end

Instance Method Details

#batchesObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 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

#optionsObject



33
34
35
# File 'lib/mongo_batch.rb', line 33

def options
  query.criteria.options
end

#with_orderObject



29
30
31
# File 'lib/mongo_batch.rb', line 29

def with_order
  options.sort ? query : query.order_by(order_by)
end