From e5c9039420d0d38e066aa2f81c46cba698d7803a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Romain=20Tarti=C3=A8re?= <romain@blogreen.org>
Date: Wed, 16 Mar 2016 20:44:46 +0100
Subject: [PATCH] Fix <=> for IPv4 and IPv6.

---
 lib/ipaddress/ipv4.rb       | 1 +
 lib/ipaddress/ipv6.rb       | 1 +
 test/ipaddress/ipv4_test.rb | 6 ++++++
 test/ipaddress/ipv6_test.rb | 6 ++++++
 4 files changed, 14 insertions(+)

diff --git a/lib/ipaddress/ipv4.rb b/lib/ipaddress/ipv4.rb
index 7d8e0d3..5e456f6 100644
--- a/lib/ipaddress/ipv4.rb
+++ b/lib/ipaddress/ipv4.rb
@@ -509,6 +509,7 @@ module IPAddress;
     #     #=> ["10.100.100.1/8","10.100.100.1/16","172.16.0.1/16"]
     #
     def <=>(oth)
+      return nil unless oth.is_a?(self.class)
       return prefix <=> oth.prefix if to_u32 == oth.to_u32  
       to_u32 <=> oth.to_u32
     end
diff --git a/lib/ipaddress/ipv6.rb b/lib/ipaddress/ipv6.rb
index 88098bc..e6e8d04 100644
--- a/lib/ipaddress/ipv6.rb
+++ b/lib/ipaddress/ipv6.rb
@@ -487,6 +487,7 @@ module IPAddress;
     #     #=> ["2001:db8:1::1/64","2001:db8:1::1/65","2001:db8:2::1/64"]
     #
     def <=>(oth)
+      return nil unless oth.is_a?(self.class)
       return prefix <=> oth.prefix if to_u128 == oth.to_u128  
       to_u128 <=> oth.to_u128
     end
diff --git a/test/ipaddress/ipv4_test.rb b/test/ipaddress/ipv4_test.rb
index 19264e2..33b3a31 100644
--- a/test/ipaddress/ipv4_test.rb
+++ b/test/ipaddress/ipv4_test.rb
@@ -372,6 +372,12 @@ class IPv4Test < Minitest::Test
     ip3 = @klass.new("10.0.0.0/8")
     arr = ["10.0.0.0/8","10.0.0.0/16","10.0.0.0/24"]
     assert_equal arr, [ip1,ip2,ip3].sort.map{|s| s.to_string}
+    # compare with alien thing
+    ip1 = @klass.new('127.0.0.1')
+    ip2 = IPAddress::IPv6.new('::1')
+    not_ip = String
+    assert_equal nil, ip1 <=> ip2
+    assert_equal nil, ip1 <=> not_ip
   end
 
   def test_method_minus
diff --git a/test/ipaddress/ipv6_test.rb b/test/ipaddress/ipv6_test.rb
index dcfb601..60f01eb 100644
--- a/test/ipaddress/ipv6_test.rb
+++ b/test/ipaddress/ipv6_test.rb
@@ -254,6 +254,12 @@ class IPv6Test < Minitest::Test
     arr = ["2001:db8:1::1/64","2001:db8:1::1/65",
            "2001:db8:1::2/64","2001:db8:2::1/64"]
     assert_equal arr, [ip1,ip2,ip3,ip4].sort.map{|s| s.to_string}
+    # compare with alien thing
+    ip1 = @klass.new('::1')
+    ip2 = IPAddress::IPv4.new('127.0.0.1')
+    not_ip = String
+    assert_equal nil, ip1 <=> ip2
+    assert_equal nil, ip1 <=> not_ip
   end
 
   def test_classmethod_expand
-- 
GitLab