From 2ae6bdcb30491df82b8b5523379a31529bc1ef25 Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Mon, 7 Aug 2017 17:19:25 -0600 Subject: [PATCH] Add == methods for IPv4 and IPv6 ActiveRecord requires these methods for seriaization. <=> is insufficient --- lib/ipaddress/ipv4.rb | 7 +++++++ lib/ipaddress/ipv6.rb | 7 +++++++ test/ipaddress/ipv4_test.rb | 4 ++++ test/ipaddress/ipv6_test.rb | 4 ++++ 4 files changed, 22 insertions(+) diff --git a/lib/ipaddress/ipv4.rb b/lib/ipaddress/ipv4.rb index a123e71..c652522 100644 --- a/lib/ipaddress/ipv4.rb +++ b/lib/ipaddress/ipv4.rb @@ -476,6 +476,13 @@ def each end end + # Equality operator + def ==(oth) + oth.class == self.class && \ + oth.to_u32 == self.to_u32 && \ + oth.prefix == self.prefix + end + # # Spaceship operator to compare IPv4 objects # diff --git a/lib/ipaddress/ipv6.rb b/lib/ipaddress/ipv6.rb index 88098bc..5e0f85f 100644 --- a/lib/ipaddress/ipv6.rb +++ b/lib/ipaddress/ipv6.rb @@ -454,6 +454,13 @@ def each end end + # Equality operator + def ==(oth) + oth.class == self.class && \ + oth.prefix == self.prefix && \ + oth.to_u128 == self.to_u128 + end + # # Spaceship operator to compare IPv6 objects # diff --git a/test/ipaddress/ipv4_test.rb b/test/ipaddress/ipv4_test.rb index 19264e2..530135e 100644 --- a/test/ipaddress/ipv4_test.rb +++ b/test/ipaddress/ipv4_test.rb @@ -363,6 +363,10 @@ def test_method_compare assert_equal true, ip1 == ip1 # ip1 should be equal to ip4 assert_equal true, ip1 == ip4 + # ip1 should be unequal to ip2 + assert_equal false, ip1 == ip2 + # ip1 should be unequal to nil + assert_equal false, ip1 == nil # test sorting arr = ["10.1.1.1/8","10.1.1.1/16","172.16.1.1/14"] assert_equal arr, [ip1,ip2,ip3].sort.map{|s| s.to_string} diff --git a/test/ipaddress/ipv6_test.rb b/test/ipaddress/ipv6_test.rb index dcfb601..11e289f 100644 --- a/test/ipaddress/ipv6_test.rb +++ b/test/ipaddress/ipv6_test.rb @@ -250,6 +250,10 @@ def test_method_compare # ip4 should be greater than ip1 assert_equal true, ip1 < ip4 assert_equal false, ip1 > ip4 + # ip1 should be unequal to ip2 + assert_equal false, ip1 == ip2 + # ip1 should be unequal to nil + assert_equal false, ip1 == nil # test sorting arr = ["2001:db8:1::1/64","2001:db8:1::1/65", "2001:db8:1::2/64","2001:db8:2::1/64"]