Sha256: 62769d09592cd5ddad36ca526558ffc823976492a112eb1900978b4a38153b0b

Contents?: true

Size: 1.24 KB

Versions: 1

Compression:

Stored size: 1.24 KB

Contents

module Mongoid
  module Criterion
    module Scrollable

      def scroll(cursor = nil, &block)
        c = self
        # we don't support scrolling over a criteria with multiple fields
        if c.options[:sort] && c.options[:sort].keys.count != 1
          sort = c.options[:sort].keys.join(", ")
          raise Mongoid::Scroll::Errors::MultipleSortFieldsError.new(sort: sort)
        end
        # introduce a default sort order if there's none
        c = c.asc(:_id) if (! c.options[:sort]) || c.options[:sort].empty?
        # scroll field and direction
        scroll_field = c.options[:sort].keys.first
        scroll_direction = c.options[:sort].values.first.to_i == 1 ? '$gt' : '$lt'
        # scroll cursor from the parameter, with value and tiebreak_id
        field = c.klass.fields[scroll_field.to_s]
        cursor_options = { field: field, direction: scroll_direction }
        cursor = cursor.is_a?(Mongoid::Scroll::Cursor) ? cursor : Mongoid::Scroll::Cursor.new(cursor, cursor_options)
        # scroll
        if block_given?
          c.where(cursor.criteria).each do |record|
            yield record, Mongoid::Scroll::Cursor.from_record(record, cursor_options)
          end
        else
          c
        end
      end

    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mongoid-scroll-0.1.0 lib/mongoid/criterion/scrollable.rb