From 3a1b27155898181a0e864ec92b519086f532287e Mon Sep 17 00:00:00 2001 From: Lucas Renan Date: Fri, 31 Dec 2010 18:59:57 -0200 Subject: [PATCH] add method 'last' to simplify queries --- lib/couchrest/model/class_proxy.rb | 6 ++++++ lib/couchrest/model/document_queries.rb | 16 ++++++++++++++++ spec/couchrest/class_proxy_spec.rb | 6 ++++++ spec/couchrest/view_spec.rb | 6 ++++++ 4 files changed, 34 insertions(+) diff --git a/lib/couchrest/model/class_proxy.rb b/lib/couchrest/model/class_proxy.rb index 36200f9..3f988b1 100644 --- a/lib/couchrest/model/class_proxy.rb +++ b/lib/couchrest/model/class_proxy.rb @@ -75,6 +75,12 @@ module CouchRest doc end + def last(opts = {}) + doc = @klass.last({:database => @database}.merge(opts)) + doc.database = @database if doc && doc.respond_to?(:database) + doc + end + def get(id) doc = @klass.get(id, @database) doc.database = @database if doc && doc.respond_to?(:database) diff --git a/lib/couchrest/model/document_queries.rb b/lib/couchrest/model/document_queries.rb index 48ec485..575a675 100644 --- a/lib/couchrest/model/document_queries.rb +++ b/lib/couchrest/model/document_queries.rb @@ -38,6 +38,22 @@ module CouchRest first_instance.empty? ? nil : first_instance.first end + # Load the last document that have the model_type_key's field equal to + # the name of the current class. + # It's similar to method first, just adds :descending => true + # + # ==== Returns + # Object:: The last object instance available + # or + # Nil:: if no instances available + # + # ==== Parameters + # opts:: + # View options, see CouchRest::Database#view options for more info. + def last(opts = {}) + first(opts.merge!(:descending => true)) + end + # Load a document from the database by id # No exceptions will be raised if the document isn't found # diff --git a/spec/couchrest/class_proxy_spec.rb b/spec/couchrest/class_proxy_spec.rb index cba0e38..fc89533 100644 --- a/spec/couchrest/class_proxy_spec.rb +++ b/spec/couchrest/class_proxy_spec.rb @@ -87,6 +87,12 @@ describe "Proxy Class" do u = @us.first u.title.should =~ /\A...\z/ end + + it "should get last" do + u = @us.last + u.title.should == "aaa" + end + it "should set database on first retreived document" do u = @us.first u.database.should === DB diff --git a/spec/couchrest/view_spec.rb b/spec/couchrest/view_spec.rb index 5f1ec64..59ab062 100644 --- a/spec/couchrest/view_spec.rb +++ b/spec/couchrest/view_spec.rb @@ -273,6 +273,12 @@ describe "Model views" do u = Unattached.first :database=>@db u.title.should =~ /\A...\z/ end + + it "should get last" do + u = Unattached.last :database=>@db + u.title.should == "aaa" + end + it "should barf on all_design_doc_versions if no database given" do lambda{Unattached.all_design_doc_versions}.should raise_error end