diff --git a/couchrest.gemspec b/couchrest.gemspec index 118794b..bad5e82 100644 --- a/couchrest.gemspec +++ b/couchrest.gemspec @@ -1,6 +1,6 @@ Gem::Specification.new do |s| s.name = "couchrest" - s.version = "0.8.1" + s.version = "0.8.2" s.date = "2008-06-20" s.summary = "Lean and RESTful interface to CouchDB." s.email = "jchris@grabb.it" diff --git a/lib/pager.rb b/lib/pager.rb index b59dc1e..10b97c3 100644 --- a/lib/pager.rb +++ b/lib/pager.rb @@ -32,6 +32,22 @@ class CouchRest @db = db end + def all_docs(count=100, &block) + startkey = nil + keepgoing = true + oldend = nil + + while docrows = request_all_docs(count+1, startkey) + startkey = docrows.last['key'] + docrows.pop if docrows.length > count + if oldend == startkey + break + end + yield(docrows) + oldend = startkey + end + end + def key_reduce(view, count, firstkey = nil, lastkey = nil, &block) # start with no keys startkey = firstkey @@ -81,6 +97,17 @@ class CouchRest end end + private + + def request_all_docs count, startkey = nil + opts = {} + opts[:count] = count if count + opts[:startkey] = startkey if startkey + results = @db.documents(opts) + rows = results['rows'] + rows unless rows.length == 0 + end + def request_view view, count = nil, startkey = nil, endkey = nil opts = {} opts[:count] = count if count diff --git a/spec/database_spec.rb b/spec/database_spec.rb index 49e57dc..2ea09e4 100644 --- a/spec/database_spec.rb +++ b/spec/database_spec.rb @@ -4,14 +4,12 @@ describe CouchRest::Database do before(:each) do @cr = CouchRest.new(COUCHHOST) begin - @db = @cr.create_db(TESTDB) + @db = @cr.database(TESTDB) + @db.delete! rescue RestClient::Request::RequestFailed end - end - - after(:each) do begin - @db.delete! + @db = @cr.create_db(TESTDB) rescue RestClient::Request::RequestFailed end end diff --git a/spec/pager_spec.rb b/spec/pager_spec.rb index 80717b6..f1c5b4d 100644 --- a/spec/pager_spec.rb +++ b/spec/pager_spec.rb @@ -25,6 +25,39 @@ describe CouchRest::Pager do @pager.db.should == @db end + describe "paging all docs" do + before(:all) do + @docs = [] + 100.times do |i| + @docs << ({:number => (i % 10)}) + end + @db.bulk_save(@docs) + end + it "should yield total_docs / count times" do + n = 0 + @pager.all_docs(10) do |doc| + n += 1 + end + n.should == 10 + end + it "should yield each docrow group without duplicate docs" do + docids = {} + @pager.all_docs(10) do |docrows| + docrows.each do |row| + docids[row['id']].should be_nil + docids[row['id']] = true + end + end + docids.keys.length.should == 100 + end + it "should yield each docrow group" do + @pager.all_docs(10) do |docrows| + doc = @db.get(docrows[0]['id']) + doc['number'].class.should == Fixnum + end + end + end + describe "Pager with a view and docs" do before(:all) do @docs = []