lib/plucky/query.rb in plucky-0.2.1 vs lib/plucky/query.rb in plucky-0.3.0
- old
+ new
@@ -1,19 +1,21 @@
# encoding: UTF-8
require 'forwardable'
module Plucky
class Query
- extend Forwardable
+ include Enumerable
+ extend Forwardable
OptionKeys = [
:select, :offset, :order, # MM
:fields, :skip, :limit, :sort, :hint, :snapshot, :batch_size, :timeout # Ruby Driver
]
- attr_reader :criteria, :options, :collection
- def_delegator :criteria, :simple?
- def_delegator :options, :fields?
+ attr_reader :criteria, :options, :collection
+ def_delegator :criteria, :simple?
+ def_delegator :options, :fields?
+ def_delegators :to_a, :each
def initialize(collection, opts={})
@collection, @options, @criteria = collection, OptionsHash.new, CriteriaHash.new
opts.each { |key, value| self[key] = value }
end
@@ -48,11 +50,11 @@
docs.extend(Pagination::Decorator)
docs.paginator(paginator)
end
end
- def find_many(opts={})
+ def find_each(opts={})
query = clone.update(opts)
query.collection.find(query.criteria.to_hash, query.options.to_hash)
end
def find_one(opts={})
@@ -68,11 +70,11 @@
all(:_id => ids.flatten)
end
end
def all(opts={})
- find_many(opts).to_a
+ find_each(opts).to_a
end
def first(opts={})
find_one(opts)
end
@@ -85,13 +87,17 @@
query = clone.update(opts)
query.collection.remove(query.criteria.to_hash)
end
def count(opts={})
- find_many(opts).count
+ find_each(opts).count
end
+ def size
+ count
+ end
+
def update(opts={})
opts.each { |key, value| self[key] = value }
self
end
@@ -121,9 +127,17 @@
def where(hash={})
clone.tap do |query|
query.criteria.merge!(CriteriaHash.new(hash))
end
+ end
+
+ def empty?
+ count.zero?
+ end
+
+ def to_a
+ all
end
def [](key)
key = key.to_sym if key.respond_to?(:to_sym)
if OptionKeys.include?(key)
\ No newline at end of file