Skip to content

Instantly share code, notes, and snippets.

@edvardm
Last active December 29, 2015 12:59
Show Gist options
  • Save edvardm/7674687 to your computer and use it in GitHub Desktop.
Save edvardm/7674687 to your computer and use it in GitHub Desktop.
Simple worker that does stuff in batches. Block passed to initializer should be a method that accepts list of things to work at a time
class BatchWorker
attr_reader :size
def initialize(size, &block)
@size = size
@buf = []
@block = block
end
def write(value)
@buf << value
if @buf.size >= @size
@block.call(@buf)
@buf.clear
end
end
def finish
@block.call(@buf)
end
end
# w = BatchWorker.new(3) { |numbers| puts numbers.inspect }
# (1..10).each { |i| w.write(i) }
# => [1, 2, 3]
# => [4, 5, 6]
# => [7, 8, 9]
# w.finish
# => [10]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment