diff --git a/history.txt b/history.txt index a967347..1ed65ca 100644 --- a/history.txt +++ b/history.txt @@ -2,6 +2,7 @@ * Minor enhancements: * Adding "couchrest-hash" to Design Docs with aim to improve view update handling. + * Using #descending on View object will automatically swap startkey with endkey. == 1.1.0.beta2 diff --git a/lib/couchrest/model/designs/view.rb b/lib/couchrest/model/designs/view.rb index 95c4ea4..ed6963d 100644 --- a/lib/couchrest/model/designs/view.rb +++ b/lib/couchrest/model/designs/view.rb @@ -239,11 +239,19 @@ module CouchRest end - # The results should be provided in descending order. + # The results should be provided in descending order. If the startkey or + # endkey query options have already been seen set, calling this method + # will automatically swap the options around. If you don't want this, + # simply set descending before any other option. # - # Descending is false by default, this method will enable it and cannot - # be undone. + # Descending is false by default, and this method cannot + # be undone once used, it has no inverse option. def descending + if query[:startkey] || query[:endkey] + query[:startkey], query[:endkey] = query[:endkey], query[:startkey] + elsif query[:startkey_docid] || query[:endkey_docid] + query[:startkey_docid], query[:endkey_docid] = query[:endkey_docid], query[:startkey_docid] + end update_query(:descending => true) end diff --git a/spec/couchrest/designs/view_spec.rb b/spec/couchrest/designs/view_spec.rb index 0bf0307..4221751 100644 --- a/spec/couchrest/designs/view_spec.rb +++ b/spec/couchrest/designs/view_spec.rb @@ -386,6 +386,24 @@ describe "Design View" do @obj.should_receive(:update_query).with({:descending => true}) @obj.descending end + it "should reverse start and end keys if given" do + @obj = @obj.startkey('a').endkey('z') + @obj = @obj.descending + @obj.query[:endkey].should eql('a') + @obj.query[:startkey].should eql('z') + end + it "should reverse even if start or end nil" do + @obj = @obj.startkey('a') + @obj = @obj.descending + @obj.query[:endkey].should eql('a') + @obj.query[:startkey].should be_nil + end + it "should reverse start_doc and end_doc keys if given" do + @obj = @obj.startkey_doc('a').endkey_doc('z') + @obj = @obj.descending + @obj.query[:endkey_docid].should eql('a') + @obj.query[:startkey_docid].should eql('z') + end end describe "#limit" do