diff --git a/lib/couchrest/mixins/design_doc.rb b/lib/couchrest/mixins/design_doc.rb index 068a29d..6f1fb2a 100644 --- a/lib/couchrest/mixins/design_doc.rb +++ b/lib/couchrest/mixins/design_doc.rb @@ -35,8 +35,11 @@ module CouchRest 'all' => { 'map' => "function(doc) { if (doc['couchrest-type'] == '#{self.to_s}') { - emit(null,null); + emit(null,1); } + }", + 'reduce' => "function(keys, values) { + return sum(values); }" } } diff --git a/lib/couchrest/mixins/document_queries.rb b/lib/couchrest/mixins/document_queries.rb index 6834429..3ea516c 100644 --- a/lib/couchrest/mixins/document_queries.rb +++ b/lib/couchrest/mixins/document_queries.rb @@ -12,9 +12,18 @@ module CouchRest # name of the current class. Take the standard set of # CouchRest::Database#view options. def all(opts = {}, &block) - view(:all, opts, &block) + view(:all, {:reduce => false}.merge(opts), &block) end - + + # Returns the number of documents that have the "couchrest-type" field + # equal to the name of the current class. Takes the standard set of + # CouchRest::Database#view options + def count(opts = {}, &block) + result = all({:reduce => true}.merge(opts), &block)['rows'] + return 0 if result.empty? + result.first['value'] + end + # Load the first document that have the "couchrest-type" field equal to # the name of the current class. # diff --git a/spec/couchrest/more/extended_doc_spec.rb b/spec/couchrest/more/extended_doc_spec.rb index 257614f..ad4c11f 100644 --- a/spec/couchrest/more/extended_doc_spec.rb +++ b/spec/couchrest/more/extended_doc_spec.rb @@ -241,7 +241,25 @@ describe "ExtendedDocument" do rs.length.should == 4 end end - + + describe "counting all instances of a model" do + before(:each) do + @db = reset_test_db! + end + + it ".count should return 0 if there are no docuemtns" do + WithTemplateAndUniqueID.count.should == 0 + end + + it ".count should return the number of documents" do + WithTemplateAndUniqueID.new('important-field' => '1').save + WithTemplateAndUniqueID.new('important-field' => '2').save + WithTemplateAndUniqueID.new('important-field' => '3').save + + WithTemplateAndUniqueID.count.should == 3 + end + end + describe "finding the first instance of a model" do before(:each) do @db = reset_test_db!