Class: Mongo::CachingCursor

Inherits:
Cursor
  • Object
show all
Defined in:
build/ruby-driver-v2.19/lib/mongo/caching_cursor.rb

Overview

A Cursor that attempts to load documents from memory first before hitting the database if the same query has already been executed.

Instance Attribute Summary collapse

Attributes inherited from Cursor

#initial_result, #resume_token, #server, #view

Instance Method Summary collapse

Methods inherited from Cursor

#batch_size, #close, #closed?, #collection_name, finalize, #fully_iterated?, #get_more, #id, #initialize, #kill_spec, #to_return

Methods included from Retryable

#read_worker, #select_server, #write_worker

Constructor Details

This class inherits a constructor from Mongo::Cursor

Instance Attribute Details

#cached_docsArray <BSON::Document> (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns The cursor’s cached documents.

Returns:

  • (Array <BSON::Document>)

    The cursor’s cached documents.



28
29
30
# File 'build/ruby-driver-v2.19/lib/mongo/caching_cursor.rb', line 28

def cached_docs
  @cached_docs
end

Instance Method Details

#eachObject

We iterate over the cached documents if they exist already in the cursor otherwise proceed as normal.

Examples:

Iterate over the documents.

cursor.each do |doc|
  # ...
end


37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'build/ruby-driver-v2.19/lib/mongo/caching_cursor.rb', line 37

def each
  if @cached_docs
    @cached_docs.each do |doc|
      yield doc
    end

    unless closed?
      # StopIteration raised by try_next ends this loop.
      loop do
        document = try_next
        yield document if document
      end
    end
  else
    super
  end
end

#inspectString

Get a human-readable string representation of Cursor.

Examples:

Inspect the cursor.

cursor.inspect

Returns:

  • (String)

    A string representation of a Cursor instance.



61
62
63
# File 'build/ruby-driver-v2.19/lib/mongo/caching_cursor.rb', line 61

def inspect
  "#<Mongo::CachingCursor:0x#{object_id} @view=#{@view.inspect}>"
end

#try_nextObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Acquires the next document for cursor iteration and then inserts that document in the @cached_docs array.



69
70
71
72
73
74
75
# File 'build/ruby-driver-v2.19/lib/mongo/caching_cursor.rb', line 69

def try_next
  @cached_docs ||= []
  document = super
  @cached_docs << document if document

  document
end