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 6ae651d..f37ac53 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 7eaa765..344466a 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