Skip to content

Commit

Permalink
Merge pull request #31 from nhemsley/master
Browse files Browse the repository at this point in the history
add eql? and hash methods to table object for using objects as hash keys
  • Loading branch information
sirupsen authored Nov 5, 2018
2 parents 71c1096 + 97cf751 commit 6d557e3
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
10 changes: 8 additions & 2 deletions lib/airrecord/table.rb
Original file line number Diff line number Diff line change
Expand Up @@ -215,19 +215,25 @@ def serializable_fields(fields = self.fields)
value = [ value ] unless value.is_a?(Enumerable)
assocs = value.map { |assoc|
assoc.respond_to?(:id) ? assoc.id : assoc
}
}
[key, assocs]
else
[key, value]
end
}]
end

def ==(other)
self.class == other.class &&
serializable_fields == other.serializable_fields
end

alias_method :eql?, :==

def hash
serializable_fields.hash
end

protected

def association(key)
Expand Down
30 changes: 29 additions & 1 deletion test/table_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ def test_comparison_different_classes
end

def test_association_accepts_non_enumerable
walrus = Walrus.new("Name" => "Wally")
walrus = Walrus.new("Name" => "Wally")
foot = Foot.new("Name" => "FrontRight", "walrus" => walrus)

foot.serializable_fields
Expand All @@ -315,4 +315,32 @@ def test_dont_update_if_equal
walrus["Name"] = "Wally"
assert walrus.updated_keys.empty?
end

def test_equivalent_records_are_eql?
walrus1 = Walrus.new("Name" => "Wally")
walrus2 = Walrus.new("Name" => "Wally")

assert walrus1.eql? walrus2
end

def test_non_equivalent_records_fail_eql?
walrus1 = Walrus.new("Name" => "Wally")
walrus2 = Walrus.new("Name" => "Wally2")

assert !walrus1.eql?(walrus2)
end

def test_equivalent_hash_equality
walrus1 = Walrus.new("Name" => "Wally")
walrus2 = Walrus.new("Name" => "Wally")

assert_equal walrus1.hash, walrus2.hash
end

def test_non_equivalent_hash_inequality
walrus1 = Walrus.new("Name" => "Wally")
walrus2 = Walrus.new("Name" => "Wally2")

assert walrus1.hash != walrus2.hash
end
end

0 comments on commit 6d557e3

Please sign in to comment.