Module: Mongo::Scrollable

Defined in:
lib/mongo/scrollable.rb

Instance Method Summary collapse

Instance Method Details

#scroll(cursor = nil, options = nil, &_block) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/mongo/scrollable.rb', line 3

def scroll(cursor = nil, options = nil, &_block)
  view = self
  # we don't support scrolling over a view with multiple fields
  raise Mongoid::Scroll::Errors::MultipleSortFieldsError.new(sort: view.sort) if view.sort && view.sort.keys.size != 1
  # scroll field and direction
  scroll_field = view.sort ? view.sort.keys.first : :_id
  scroll_direction = view.sort ? view.sort.values.first.to_i : 1
  # scroll cursor from the parameter, with value and tiebreak_id
  options = { field_type: BSON::ObjectId } unless options
  cursor_options = { field_name: scroll_field, direction: scroll_direction }.merge(options)
  cursor = cursor.is_a?(Mongoid::Scroll::Cursor) ? cursor : Mongoid::Scroll::Cursor.new(cursor, cursor_options)
  # make a view
  view = Mongo::Collection::View.new(
    view.collection,
    view.selector.merge(cursor.criteria),
    sort: (view.sort || {}).merge(_id: scroll_direction),
    skip: skip,
    limit: limit
  )
  # scroll
  if block_given?
    view.each do |record|
      yield record, Mongoid::Scroll::Cursor.from_record(record, cursor_options)
    end
  else
    view
  end
end