Skip to content
This repository has been archived by the owner on Jan 15, 2024. It is now read-only.

Commit

Permalink
Add @cache to Moped::Cursor for out-of-block iteration
Browse files Browse the repository at this point in the history
The Mongo Ruby driver (and thus Mongoid 2.x) supported iterating over a
cursor outside a block, using such operations as take(). For example:

    batch_size = 10
    cursor = session[:users].find({}).cursor
    while (users = cursor.take(batch_size)).present?
      # Do stuff...
    end
    # Do more stuff...

This was a convenient pattern for implementing lots of algorithms in a
more readable way than if they were written using each().
  • Loading branch information
Frank Macreery committed Nov 27, 2013
1 parent 073e30b commit 2d854a0
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
10 changes: 5 additions & 5 deletions lib/moped/cursor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class Cursor
# @attribute [r] kill_cursor_op The kill cursor message.
# @attribute [r] query_op The query message.
# @attribute [r] session The session.
attr_reader :get_more_op, :kill_cursor_op, :query_op, :session
attr_reader :get_more_op, :kill_cursor_op, :query_op, :session, :cache

# Iterate over the results of the query.
#
Expand All @@ -24,12 +24,12 @@ class Cursor
#
# @since 1.0.0
def each
documents = load_docs
documents.each { |doc| yield doc }
@cache ||= load_docs
yield @cache.shift while @cache.any?
while more?
return kill if limited? && @limit <= 0
documents = get_more
documents.each { |doc| yield doc }
@cache = get_more
yield @cache.shift while @cache.any?
end
end

Expand Down
20 changes: 20 additions & 0 deletions spec/moped/cursor_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -67,5 +67,25 @@
cursor.request_limit.should eq(100)
end
end

context "when the cursor is iterated upon out-of-block" do

before do
session[:users].insert({ "name" => "create" })
end

let(:query) do
session[:users].find.limit(1)
end

let(:cursor) do
described_class.new(session, query.operation)
end

it "advances the cursor_id" do
cursor.take(1)
cursor.take(1).should be_empty
end
end
end
end

0 comments on commit 2d854a0

Please sign in to comment.