From 778e486328c7b4e69bbaf4e6990a7e8fa2a42704 Mon Sep 17 00:00:00 2001 From: Sam Lown Date: Thu, 9 Jun 2011 01:49:09 +0200 Subject: [PATCH] Adding comparison using ids rather than hashes --- lib/couchrest/model/base.rb | 15 +++++++++++++++ spec/fixtures/models/project.rb | 6 ++++++ spec/unit/base_spec.rb | 19 ++++++++++++++++++- 3 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 spec/fixtures/models/project.rb diff --git a/lib/couchrest/model/base.rb b/lib/couchrest/model/base.rb index 8ae8cac..7b6255a 100644 --- a/lib/couchrest/model/base.rb +++ b/lib/couchrest/model/base.rb @@ -92,6 +92,21 @@ module CouchRest alias :to_param :id alias :new_record? :new? alias :new_document? :new? + + # Compare this model with another by confirming to see + # if the IDs and their databases match! + # + # Camparison of the database is required in case the + # model has been proxied or loaded elsewhere. + # + # A Basic CouchRest document will only ever compare using + # a Hash comparison on the attributes. + def == other + return false unless other.is_a?(Base) + database == other.database && id == other.id + end + alias :eql? :== + end end end diff --git a/spec/fixtures/models/project.rb b/spec/fixtures/models/project.rb new file mode 100644 index 0000000..d8de244 --- /dev/null +++ b/spec/fixtures/models/project.rb @@ -0,0 +1,6 @@ +class Project < CouchRest::Model::Base + use_database DB + property :name, String + timestamps! + view_by :name +end diff --git a/spec/unit/base_spec.rb b/spec/unit/base_spec.rb index c375a7c..fb17f0a 100644 --- a/spec/unit/base_spec.rb +++ b/spec/unit/base_spec.rb @@ -142,8 +142,25 @@ describe "Model Base" do @obj.destroyed?.should be_true end end + end - + describe "comparisons" do + describe "#==" do + it "should be true on same document" do + p = Project.create + p.should eql(p) + end + it "should be true after loading" do + p = Project.create + p.should eql(Project.get(p.id)) + end + it "should not be true if databases do not match" do + p = Project.create + p2 = p.dup + p2.stub!(:database).and_return('other') + p.should_not eql(p2) + end + end end describe "update attributes without saving" do