Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for IPAddress.as_json #90

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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