Class: CanvasSync::BatchProcessor

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

Overview

An array that “processes” after so many items are added.

Example Usage:

batches = CanvasSync::BatchProcessor.new(of: 1000) do |batch|
  # Process the batch somehow
end
enumerator_of_some_kind.each { |item| batches << item }
batches.flush

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(of: 1000, &blk) ⇒ BatchProcessor

Returns a new instance of BatchProcessor.



13
14
15
16
17
# File 'lib/canvas_sync/batch_processor.rb', line 13

def initialize(of: 1000, &blk)
  @batch_size = of
  @block = blk
  @current_batch = []
end

Instance Attribute Details

#batch_sizeObject (readonly)

Returns the value of attribute batch_size.



11
12
13
# File 'lib/canvas_sync/batch_processor.rb', line 11

def batch_size
  @batch_size
end

Instance Method Details

#<<(item) ⇒ Object



19
20
21
22
# File 'lib/canvas_sync/batch_processor.rb', line 19

def <<(item)
  @current_batch << item
  process_batch if @current_batch.count >= batch_size
end

#add_all(items) ⇒ Object



24
25
26
27
28
# File 'lib/canvas_sync/batch_processor.rb', line 24

def add_all(items)
  items.each do |i|
    self << i
  end
end

#flushObject



30
31
32
# File 'lib/canvas_sync/batch_processor.rb', line 30

def flush
  process_batch if @current_batch.present?
end