Created
November 10, 2015 14:50
-
-
Save szajbus/5dc54ddb3c29fcf8b494 to your computer and use it in GitHub Desktop.
Commitable buffer
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 Buffer | |
def initialize(size = 1_000, &blk) | |
@size = size | |
@callback = blk | |
@queue = [] | |
@lock = Mutex.new | |
end | |
def <<(object) | |
@lock.synchronize do | |
@queue << object | |
commit! if @queue.size >= @size | |
end | |
self | |
end | |
def commit! | |
if @queue.any? | |
@callback.call(@queue) | |
@queue = [] | |
end | |
end | |
end |
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
# Set up buffer with commit callback as block | |
buffer = Buffer.new do |docs| | |
ElasticSearch.bulk(docs, :local) | |
logger.increase_current_step | |
end | |
# Process products, keep adding results to buffer | |
products.each do |p| | |
... | |
buffer << p | |
end | |
# Commit what is left in buffer | |
buffer.commit! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment