Skip to content

Commit d7cccb0

Browse files
committed
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
1 parent 2a10d48 commit d7cccb0

4 files changed

Lines changed: 34 additions & 0 deletions

File tree

lib/ipaddress/ipv4.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,18 @@ def address
104104
@address
105105
end
106106

107+
#
108+
# When serializing to JSON format, just use the string representation
109+
#
110+
# ip = IPAddress("172.16.100.4/22")
111+
#
112+
# ip.as_json
113+
# #=> "172.16.100.4/22"
114+
#
115+
def as_json
116+
to_string
117+
end
118+
107119
#
108120
# Returns the prefix portion of the IPv4 object
109121
# as a IPAddress::Prefix32 object

lib/ipaddress/ipv6.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,18 @@ def address
117117
@address
118118
end
119119

120+
#
121+
# When serializing to JSON format, just use the string representation
122+
#
123+
# ip = IPAddress "2001:db8::8:800:200c:417a/64"
124+
#
125+
# ip.as_json
126+
# #=> "2001:db8::8:800:200c:417a/64"
127+
#
128+
def as_json
129+
to_string
130+
end
131+
120132
#
121133
# Returns an array with the 16 bits groups in decimal
122134
# format:

test/ipaddress/ipv4_test.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,11 @@ def test_initialize_should_require_ip
118118
assert_raises(ArgumentError) { @klass.new }
119119
end
120120

121+
def test_method_as_json
122+
ip = @klass.new("172.16.100.4/22")
123+
assert_equal "172.16.100.4/22", ip.as_json
124+
end
125+
121126
def test_method_data
122127
if RUBY_VERSION < "2.0"
123128
assert_equal "\254\020\n\001", @ip.data

test/ipaddress/ipv6_test.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,11 @@ def test_attribute_groups
6767
assert_equal @arr, @ip.groups
6868
end
6969

70+
def test_method_as_json
71+
ip = @klass.new("2001:db8::8:800:200c:417a/64")
72+
assert_equal "2001:db8::8:800:200c:417a/64", ip.as_json
73+
end
74+
7075
def test_method_hexs
7176
arr = "2001:0db8:0000:0000:0008:0800:200c:417a".split(":")
7277
assert_equal arr, @ip.hexs

0 commit comments

Comments
 (0)