Skip to content

Commit

Permalink
Added eql? and hash on Document to support [].uniq in an expected man…
Browse files Browse the repository at this point in the history
…ner.
  • Loading branch information
Nicklas Ramhoj and Patrik Sjöberg committed Feb 10, 2010
1 parent 26c6a25 commit e07227e
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
11 changes: 11 additions & 0 deletions lib/mongoid/document.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -118,6 +118,17 @@ def ==(other)
other.attributes.except(:modified_at).except(:created_at) other.attributes.except(:modified_at).except(:created_at)
end 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 # Introduces a child object into the +Document+ object graph. This will
# set up the relationships between the parent and child and update the # set up the relationships between the parent and child and update the
# attributes of the parent +Document+. # attributes of the parent +Document+.
Expand Down
67 changes: 67 additions & 0 deletions spec/unit/mongoid/document_spec.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -67,6 +67,73 @@


end 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 describe "#alias_method_chain" do


context "on a field setter" do context "on a field setter" do
Expand Down

0 comments on commit e07227e

Please sign in to comment.