Base#==, eql?, and hash methods. == returns true if its argument is identical to self or if it's an instance of the same class, is not new?, and has the same id. eql? is an alias for ==. hash delegates to id.

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@5773 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
This commit is contained in:
Jeremy Kemper 2006-12-22 21:42:52 +00:00
parent 68d2926ab0
commit c172154054
3 changed files with 61 additions and 0 deletions

@ -1,5 +1,7 @@
*SVN*
* Base#==, eql?, and hash methods. == returns true if its argument is identical to self or if it's an instance of the same class, is not new?, and has the same id. eql? is an alias for ==. hash delegates to id. [Jeremy Kemper]
* Allow subclassed resources to share the site info [Rick, Jeremy Kemper]
class BeastResource < ActiveResource::Base

@ -111,6 +111,22 @@ def id=(id)
attributes[self.class.primary_key] = id
end
# True if and only if +other+ is the same object or is an instance of the same class, is not new?, and has the same id.
def ==(other)
other.equal?(self) || (other.instance_of?(self.class) && !other.new? && other.id == id)
end
# Delegates to ==
def eql?(other)
self == other
end
# Delegates to id in order to allow two resources of the same type and id to work with something like:
# [Person.find(1), Person.find(2)] & [Person.find(1), Person.find(4)] # => [Person.find(1)]
def hash
id.hash
end
def save
new? ? create : update
end

@ -0,0 +1,43 @@
require "#{File.dirname(__FILE__)}/../abstract_unit"
require "fixtures/person"
require "fixtures/street_address"
class BaseEqualityTest < Test::Unit::TestCase
def setup
@new = Person.new
@one = Person.new(:id => 1)
@two = Person.new(:id => 2)
@street = StreetAddress.new(:id => 2)
end
def test_should_equal_self
assert @new == @new, '@new == @new'
assert @one == @one, '@one == @one'
end
def test_shouldnt_equal_new_resource
assert @new != @one, '@new != @one'
assert @one != @new, '@one != @new'
end
def test_shouldnt_equal_different_class
assert @two != @street, 'person != street_address with same id'
assert @street != @two, 'street_address != person with same id'
end
def test_eql_should_alias_equals_operator
assert_equal @new == @new, @new.eql?(@new)
assert_equal @new == @one, @new.eql?(@one)
assert_equal @one == @one, @one.eql?(@one)
assert_equal @one == @new, @one.eql?(@new)
assert_equal @one == @street, @one.eql?(@street)
end
def test_hash_should_be_id_hash
[@new, @one, @two, @street].each do |resource|
assert_equal resource.id.hash, resource.hash
end
end
end