diff --git a/lib/mongoid/criteria.rb b/lib/mongoid/criteria.rb index 6ec403a139..23a164fda1 100644 --- a/lib/mongoid/criteria.rb +++ b/lib/mongoid/criteria.rb @@ -292,9 +292,13 @@ def merge(other) # # Returns: Criteria def method_missing(name, *args) - new_scope = @klass.send(name) - new_scope.merge(self) - new_scope + if @klass.respond_to?(name) + new_scope = @klass.send(name) + new_scope.merge(self) + return new_scope + else + return collect.send(name, *args) + end end # Adds a criterion to the +Criteria+ that specifies values where none @@ -367,11 +371,6 @@ def per_page (@options[:limit] || 20).to_i end - # Execute the criteria and collect in order to handle random requests. - def rand - collect.rand - end - # Adds a criterion to the +Criteria+ that specifies the fields that will # get returned from the Document. Used mainly for list views that do not # require all fields to be present. This is similar to SQL "SELECT" values. diff --git a/spec/unit/mongoid/criteria_spec.rb b/spec/unit/mongoid/criteria_spec.rb index 787490ec83..d4e0ed69d4 100644 --- a/spec/unit/mongoid/criteria_spec.rb +++ b/spec/unit/mongoid/criteria_spec.rb @@ -457,6 +457,34 @@ end + context "when expecting behaviour of an array" do + + before do + @array = mock + @document = mock + end + + describe "#[]" do + + it "collects the criteria and calls []" do + @criteria.expects(:collect).returns([@document]) + @criteria[0].should == @document + end + + end + + describe "#rand" do + + it "collects the criteria and call rand" do + @criteria.expects(:collect).returns(@array) + @array.expects(:send).with(:rand).returns(@document) + @criteria.rand + end + + end + + end + end describe "#not_in" do