Browse files

Added eql? and hash on Document to support [].uniq in an expected man…

…ner.
  • Loading branch information...
1 parent 26c6a25 commit e07227e590f06ce328f4a8d0ff0aaa7b75a18ee0 Nicklas Ramhoj and Patrik Sjöberg committed Feb 10, 2010
Showing with 78 additions and 0 deletions.
  1. +11 −0 lib/mongoid/document.rb
  2. +67 −0 spec/unit/mongoid/document_spec.rb
View
11 lib/mongoid/document.rb
@@ -118,6 +118,17 @@ def ==(other)
other.attributes.except(:modified_at).except(:created_at)
end
+ # Delegates to ==
+ def eql?(comparison_object)
+ self == (comparison_object)
+ end
+
+ # Delegates to id in order to allow two records of the same type and id to work with something like:
+ # [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]
+ def hash
+ id.hash
+ end
+
# Introduces a child object into the +Document+ object graph. This will
# set up the relationships between the parent and child and update the
# attributes of the parent +Document+.
View
67 spec/unit/mongoid/document_spec.rb
@@ -67,6 +67,73 @@
end
+ describe "#eql?" do
+
+ context "when other object is a Document" do
+
+ context "when attributes are equal" do
+
+ before do
+ @document = Person.new(:_id => 1, :title => "Sir")
+ @other = Person.new(:_id => 1, :title => "Sir")
+ end
+
+ it "returns true" do
+ @document.eql?(@other).should be_true
+ end
+
+ end
+
+ context "when attributes are not equal" do
+
+ before do
+ @document = Person.new(:title => "Sir")
+ @other = Person.new(:title => "Madam")
+ end
+
+ it "returns false" do
+ @document.eql?(@other).should_not be_true
+ end
+
+ end
+
+ end
+
+ context "when other object is not a Document" do
+
+ it "returns false" do
+ Person.new.eql?("Test").should be_false
+ end
+
+ end
+
+ context "when comapring parent to its subclass" do
+
+ it "returns false" do
+ Canvas.new.eql?(Firefox.new).should_not be_true
+ end
+
+ end
+
+ end
+
+ describe "#hash" do
+
+ before do
+ @document = Person.new(:_id => 1, :title => "Sir")
+ @other = Person.new(:_id => 2, :title => "Sir")
+ end
+
+ it "deligates to id" do
+ @document.hash.should == @document.id.hash
+ end
+
+ it "has unique hash per id" do
+ @document.hash.should_not == @other.hash
+ end
+
+ end
+
describe "#alias_method_chain" do
context "on a field setter" do

0 comments on commit e07227e

Please sign in to comment.