From 8c9b8ab9dd634a9a70fd541389f0aa749c7ea0a2 Mon Sep 17 00:00:00 2001 From: Nicholas Hemsley Date: Thu, 30 Aug 2018 13:28:29 +0800 Subject: [PATCH 1/3] add eql? and hash methods to table object for using objects as hash keys --- lib/airrecord/table.rb | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/lib/airrecord/table.rb b/lib/airrecord/table.rb index 2d0f44c..4467c93 100644 --- a/lib/airrecord/table.rb +++ b/lib/airrecord/table.rb @@ -196,19 +196,27 @@ 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 + def eql?(other) + self == other + end + + def hash + serializable_fields.hash + end + protected def association(key) From 97d50617f013dcb0eccb4cc65cc31be539a01b1e Mon Sep 17 00:00:00 2001 From: Nicholas Hemsley Date: Fri, 31 Aug 2018 16:18:14 +0800 Subject: [PATCH 2/3] tests for eql? and hash methods --- test/table_test.rb | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/test/table_test.rb b/test/table_test.rb index e855deb..642d732 100644 --- a/test/table_test.rb +++ b/test/table_test.rb @@ -308,7 +308,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 @@ -319,4 +319,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 From 16d219708f8c326431ef3a956c636b0e41019884 Mon Sep 17 00:00:00 2001 From: Nicholas Hemsley Date: Wed, 5 Sep 2018 07:59:42 +0800 Subject: [PATCH 3/3] use alias_method for eql? --- lib/airrecord/table.rb | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/lib/airrecord/table.rb b/lib/airrecord/table.rb index 4467c93..c751b8e 100644 --- a/lib/airrecord/table.rb +++ b/lib/airrecord/table.rb @@ -209,9 +209,7 @@ def ==(other) serializable_fields == other.serializable_fields end - def eql?(other) - self == other - end + alias_method :eql?, :== def hash serializable_fields.hash