Add .count to extended documents to return how many there are.

Adds a reduce function to the default view so that an extra view doesn't have to be maintained just for the counting.
This commit is contained in:
Will Leinweber 2009-05-23 23:44:44 -05:00 committed by Matt Aimonetti
parent e538a3881d
commit eb160e3141
3 changed files with 34 additions and 4 deletions

View file

@ -35,8 +35,11 @@ module CouchRest
'all' => { 'all' => {
'map' => "function(doc) { 'map' => "function(doc) {
if (doc['couchrest-type'] == '#{self.to_s}') { if (doc['couchrest-type'] == '#{self.to_s}') {
emit(null,null); emit(null,1);
} }
}",
'reduce' => "function(keys, values) {
return sum(values);
}" }"
} }
} }

View file

@ -12,7 +12,16 @@ module CouchRest
# name of the current class. Take the standard set of # name of the current class. Take the standard set of
# CouchRest::Database#view options. # CouchRest::Database#view options.
def all(opts = {}, &block) 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 end
# Load the first document that have the "couchrest-type" field equal to # Load the first document that have the "couchrest-type" field equal to

View file

@ -242,6 +242,24 @@ describe "ExtendedDocument" do
end end
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 describe "finding the first instance of a model" do
before(:each) do before(:each) do
@db = reset_test_db! @db = reset_test_db!