Skip to content

Instantly share code, notes, and snippets.

@ack
Created January 20, 2010 01:21
Show Gist options
  • Save ack/281494 to your computer and use it in GitHub Desktop.
Save ack/281494 to your computer and use it in GitHub Desktop.
# yield chunks (Array) of the full query to a block
# generates new Collections via self.model.all
# which has the advantage of dropping scope on
# hydrated objects
def block_batches(chunksize, &block)
new_options = self.query.options.dup
total = new_options[:limit] || self.count
new_options[:limit] = chunksize
new_options[:offset] = 0
(total / chunksize.to_f).ceil.times do |page|
yield self.model.all(new_options)
new_options[:offset] += chunksize
new_options[:limit] = [chunksize, total - new_options[:offset]].min
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment