Permalink
Browse files

Adding empty? and blank? implementations in criteria

  • Loading branch information...
1 parent 2cf722a commit 27e69bafdaf4e9b116be94ea4f7e3a602f3ca0e5 @durran durran committed Feb 8, 2010
Showing with 42 additions and 22 deletions.
  1. +12 −22 lib/mongoid/criteria.rb
  2. +30 −0 spec/unit/mongoid/criteria_spec.rb
View
34 lib/mongoid/criteria.rb
@@ -76,6 +76,17 @@ def ==(other)
end
end
+ # Returns true if the criteria is empty.
+ #
+ # Example:
+ #
+ # <tt>criteria.blank?</tt>
+ def blank?
+ count < 1
+ end
+
+ alias :empty? :blank?
+
# Return or create the context in which this criteria should be executed.
#
# This will return an Enumerable context if the class is embedded,
@@ -110,8 +121,7 @@ def fuse(criteria_conditions = {})
def each(&block)
@collection ||= execute
if block_given?
- docs = []
- @collection.each { |doc| docs << doc; yield doc }
+ @collection.each { |doc| yield doc }
end
self
end
@@ -156,26 +166,6 @@ def merge(other)
# name: The name of the class method on the +Document+ to chain.
# args: The arguments passed to the method.
#
- # Example:
- #
- # class Person
- # include Mongoid::Document
- # field :title
- # field :terms, :type => Boolean, :default => false
- #
- # class << self
- # def knights
- # all(:conditions => { :title => "Sir" })
- # end
- #
- # def accepted
- # all(:conditions => { :terms => true })
- # end
- # end
- # end
- #
- # Person.accepted.knights #returns a merged criteria of the 2 scopes.
- #
# Returns: <tt>Criteria</tt>
def method_missing(name, *args)
if @klass.respond_to?(name)
View
30 spec/unit/mongoid/criteria_spec.rb
@@ -152,6 +152,36 @@
end
+ describe "#blank?" do
+
+ before do
+ @context = stub.quacks_like(Mongoid::Contexts::Mongo.allocate)
+ @criteria.instance_variable_set(:@context, @context)
+ end
+
+ context "when the count is 0" do
+
+ before do
+ @context.expects(:count).returns(0)
+ end
+
+ it "returns true" do
+ @criteria.blank?.should be_true
+ end
+ end
+
+ context "when the count is greater than 0" do
+
+ before do
+ @context.expects(:count).returns(10)
+ end
+
+ it "returns false" do
+ @criteria.blank?.should be_false
+ end
+ end
+ end
+
describe "#context" do
context "when the context has been set" do

0 comments on commit 27e69ba

Please sign in to comment.