Sha256: f3f14ba28738077c9001f927a606c81239e8daa7174b657b567edf57f4c0ba3d

Contents?: true

Size: 1.79 KB

Versions: 1

Compression:

Stored size: 1.79 KB

Contents

module Moped
  module Scrollable
    def scroll(cursor = nil, options = nil, &_block)
      options = if Mongoid::Scroll.mongoid3?
                  { field_type: Moped::BSON::ObjectId }
                else
                  { field_type: BSON::ObjectId }
                end unless options
      query = Query.new(collection, operation.selector.dup)
      query.operation.skip = operation.skip
      query.operation.limit = operation.limit
      # we don't support scrolling over a criteria with multiple fields
      if query.operation.selector['$orderby'] && query.operation.selector['$orderby'].keys.size != 1
        raise Mongoid::Scroll::Errors::MultipleSortFieldsError.new(sort: query.operation.selector['$orderby'])
      elsif !query.operation.selector.key?('$orderby') || query.operation.selector['$orderby'].empty?
        # introduce a default sort order if there's none
        query.sort(_id: 1)
      end
      # scroll field and direction
      scroll_field = query.operation.selector['$orderby'].keys.first
      scroll_direction = query.operation.selector['$orderby'].values.first.to_i
      # scroll cursor from the parameter, with value and tiebreak_id
      cursor_options = { field_name: scroll_field, field_type: options[:field_type], direction: scroll_direction }
      cursor = cursor.is_a?(Mongoid::Scroll::Cursor) ? cursor : Mongoid::Scroll::Cursor.new(cursor, cursor_options)
      query.operation.selector['$query'] = query.operation.selector['$query'].merge(cursor.criteria)
      query.operation.selector['$orderby'] = query.operation.selector['$orderby'].merge(_id: scroll_direction)
      # scroll
      if block_given?
        query.each do |record|
          yield record, Mongoid::Scroll::Cursor.from_record(record, cursor_options)
        end
      else
        query
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mongoid-scroll-0.3.0 lib/moped/scrollable.rb