Last active
December 29, 2015 12:59
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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