Sha256: 1d092d3a609d1614fc068af44e0392c6f8bf94544c099699c93b290b5ec955bd

Contents?: true

Size: 1.32 KB

Versions: 1

Compression:

Stored size: 1.32 KB

Contents

module Mongomatic
  # Wraps a Mongo::Cursor for managing result sets from MongoDB:
  #  cursor = User.find({"zip" => 94107})
  #  user1 = cursor.next
  #
  #  User.find({"zip" => 94107}).each { |u| puts u["name"] }
  #
  #  User.find({"zip" => 94107}).count
  class Cursor
    include Enumerable

    attr_accessor :mongo_cursor

    def initialize(obj_class, mongo_cursor)
      @obj_class    = obj_class
      @mongo_cursor = mongo_cursor
    end

    def method_missing(name, *args)
      @mongo_cursor.send name, *args
    end

    # Is the cursor empty? This method is much more efficient than doing cursor.count == 0
    def empty?
      @mongo_cursor.has_next? == false
    end

    def next_document
      if doc = @mongo_cursor.next_document
        @obj_class.new(doc, false)
      end
    end

    alias :next :next_document

    def each
      @mongo_cursor.each do |doc|
        yield(@obj_class.new(doc, false))
      end
    end

    def current_limit
      @mongo_cursor.limit
    end

    def limit(number_to_return)
      @mongo_cursor.limit(number_to_return); self
    end

    def current_skip
      @mongo_cursor.skip
    end

    def skip(number_to_skip)
      @mongo_cursor.skip(number_to_skip); self
    end

    def sort(key_or_list, direction = nil)
      @mongo_cursor.sort(key_or_list, direction); self
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mongomatic-0.9.0.pre lib/mongomatic/cursor.rb