diff --git a/history.md b/history.md index 9261320..fdfd2b6 100644 --- a/history.md +++ b/history.md @@ -9,6 +9,7 @@ * Validation callbacks now support context (thanks kostia) * Document comparisons now performed using database and document ID (pointer by neocsr) * Automatic config generation now supported (thanks lucasrenan) + * Comparing documents resorts to Hash comparison if both IDs are nil. (pointer by kostia) ## 1.1.0.rc1 - 2011-06-08 diff --git a/lib/couchrest/model/base.rb b/lib/couchrest/model/base.rb index 66f3b66..53cdc42 100644 --- a/lib/couchrest/model/base.rb +++ b/lib/couchrest/model/base.rb @@ -99,7 +99,12 @@ module CouchRest # a Hash comparison on the attributes. def == other return false unless other.is_a?(Base) - database == other.database && id == other.id + if id.nil? && other.id.nil? + # no ids? assume comparing nested and revert to hash comparison + to_hash == other.to_hash + else + database == other.database && id == other.id + end end alias :eql? :== diff --git a/spec/unit/base_spec.rb b/spec/unit/base_spec.rb index 59ed673..1454a1f 100644 --- a/spec/unit/base_spec.rb +++ b/spec/unit/base_spec.rb @@ -154,19 +154,38 @@ describe "Model Base" do describe "comparisons" do describe "#==" do - it "should be true on same document" do - p = Project.create - p.should eql(p) + context "on saved document" 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 + it "should always be false if one document not saved" do + p = Project.create(:name => 'test') + o = Project.new(:name => 'test') + p.should_not eql(o) + end 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) + context "with new documents" do + it "should be true when attributes match" do + p = Project.new(:name => 'test') + o = Project.new(:name => 'test') + p.should eql(o) + end + it "should not be true when attributes don't match" do + p = Project.new(:name => 'test') + o = Project.new(:name => 'testing') + p.should_not eql(o) + end end end end