Skip to content

Commit

Permalink
Fix a stack overflow when doing IPAddress.as_json
Browse files Browse the repository at this point in the history
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 ipaddress-gem#89
  • Loading branch information
asomers committed Aug 7, 2017
1 parent 2a10d48 commit d7cccb0
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 0 deletions.
12 changes: 12 additions & 0 deletions lib/ipaddress/ipv4.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions lib/ipaddress/ipv6.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
5 changes: 5 additions & 0 deletions test/ipaddress/ipv4_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions test/ipaddress/ipv6_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit d7cccb0

Please sign in to comment.