From d7cccb045e0979ab8121d94271356a3b7611cb12 Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Mon, 7 Aug 2017 17:07:26 -0600 Subject: [PATCH] Fix a stack overflow when doing IPAddress.as_json Add IPAddress::IPv4#as_json and IPAddress::IPv6#as_json. If that method is not defined, then ActiveSupport will create it automatically, but it overflows the stack due to the way that ipaddress uses #each. Fixes #89 --- lib/ipaddress/ipv4.rb | 12 ++++++++++++ lib/ipaddress/ipv6.rb | 12 ++++++++++++ test/ipaddress/ipv4_test.rb | 5 +++++ test/ipaddress/ipv6_test.rb | 5 +++++ 4 files changed, 34 insertions(+) diff --git a/lib/ipaddress/ipv4.rb b/lib/ipaddress/ipv4.rb index a123e71..18fff95 100644 --- a/lib/ipaddress/ipv4.rb +++ b/lib/ipaddress/ipv4.rb @@ -104,6 +104,18 @@ def address @address end + # + # When serializing to JSON format, just use the string representation + # + # ip = IPAddress("172.16.100.4/22") + # + # ip.as_json + # #=> "172.16.100.4/22" + # + def as_json + to_string + end + # # Returns the prefix portion of the IPv4 object # as a IPAddress::Prefix32 object diff --git a/lib/ipaddress/ipv6.rb b/lib/ipaddress/ipv6.rb index 88098bc..a51cd56 100644 --- a/lib/ipaddress/ipv6.rb +++ b/lib/ipaddress/ipv6.rb @@ -117,6 +117,18 @@ def address @address end + # + # When serializing to JSON format, just use the string representation + # + # ip = IPAddress "2001:db8::8:800:200c:417a/64" + # + # ip.as_json + # #=> "2001:db8::8:800:200c:417a/64" + # + def as_json + to_string + end + # # Returns an array with the 16 bits groups in decimal # format: diff --git a/test/ipaddress/ipv4_test.rb b/test/ipaddress/ipv4_test.rb index 19264e2..28193c2 100644 --- a/test/ipaddress/ipv4_test.rb +++ b/test/ipaddress/ipv4_test.rb @@ -118,6 +118,11 @@ def test_initialize_should_require_ip assert_raises(ArgumentError) { @klass.new } end + def test_method_as_json + ip = @klass.new("172.16.100.4/22") + assert_equal "172.16.100.4/22", ip.as_json + end + def test_method_data if RUBY_VERSION < "2.0" assert_equal "\254\020\n\001", @ip.data diff --git a/test/ipaddress/ipv6_test.rb b/test/ipaddress/ipv6_test.rb index dcfb601..88c8ffe 100644 --- a/test/ipaddress/ipv6_test.rb +++ b/test/ipaddress/ipv6_test.rb @@ -67,6 +67,11 @@ def test_attribute_groups assert_equal @arr, @ip.groups end + def test_method_as_json + ip = @klass.new("2001:db8::8:800:200c:417a/64") + assert_equal "2001:db8::8:800:200c:417a/64", ip.as_json + end + def test_method_hexs arr = "2001:0db8:0000:0000:0008:0800:200c:417a".split(":") assert_equal arr, @ip.hexs