-
-
Save bradrees/9592599 to your computer and use it in GitHub Desktop.
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
module Mongoid | |
class Criteria | |
def each_by(by, &block) | |
idx = 0 | |
total = 0 | |
set_limit = options[:limit] | |
while (results = ordered_clone.limit(by).skip(idx)) && results.any? | |
results.each do |result| | |
return self if set_limit and set_limit >= total | |
yield result | |
total += 1 | |
idx += 1 unless result.nil? or result.deleted? | |
end | |
end | |
self | |
end | |
private | |
def ordered_clone | |
options[:sort] ? clone : clone.asc(:_id) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Added support for when a record is deleted the index counter is not incremented, preventing skipping when iterating over a collection that is being trimmed of records. Note that still if you are adding records you might get the opposite - records iterated twice.