summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTaketo Takashima <[email protected]>2023-11-16 17:53:32 +0900
committergit <[email protected]>2024-10-18 15:00:37 +0000
commiteb8cf1d60e4436bfebf52fbf4342ee6e5e18ba05 (patch)
tree8ad188409375a4ff69c7acf54bc960287d1d6c44
parent6b1268c7bf0816a250991593f1e504db428b6e30 (diff)
[ruby/ipaddr] Added to_json/as_json method
Updated to use cidr method when return address with prefix in #as_json https://github.com/ruby/ipaddr/commit/cf8181d53e
-rw-r--r--lib/ipaddr.rb16
-rw-r--r--test/test_ipaddr.rb14
2 files changed, 30 insertions, 0 deletions
diff --git a/lib/ipaddr.rb b/lib/ipaddr.rb
index dbb213c90a..b40d5c0359 100644
--- a/lib/ipaddr.rb
+++ b/lib/ipaddr.rb
@@ -227,6 +227,22 @@ class IPAddr
return str
end
+ # Returns a string containing the IP address representation with prefix.
+ def as_json(*)
+ if ipv4? && prefix == 32
+ to_s
+ elsif ipv6? && prefix == 128
+ to_s
+ else
+ cidr
+ end
+ end
+
+ # Returns a json string containing the IP address representation.
+ def to_json(*)
+ format("\"%s\"", as_json)
+ end
+
# Returns a string containing the IP address representation in
# cidr notation
def cidr
diff --git a/test/test_ipaddr.rb b/test/test_ipaddr.rb
index 3e5c3d2aa4..f2b7ed713f 100644
--- a/test/test_ipaddr.rb
+++ b/test/test_ipaddr.rb
@@ -260,6 +260,20 @@ class TC_IPAddr < Test::Unit::TestCase
assert_equal("3ffe:505:2::1", IPAddr.new("3ffe:505:2::1").to_s)
end
+ def test_as_json
+ assert_equal("192.168.1.2", IPAddr.new("192.168.1.2").as_json)
+ assert_equal("192.168.1.0/24", IPAddr.new("192.168.1.2/24").as_json)
+ assert_equal("2001:200:300::1", IPAddr.new("2001:200:300::1").as_json)
+ assert_equal("2001:200:300::/48", IPAddr.new("2001:200:300::/48").as_json)
+ end
+
+ def test_to_json
+ assert_equal("\"192.168.1.2\"", IPAddr.new("192.168.1.2").to_json)
+ assert_equal("\"192.168.1.0/24\"", IPAddr.new("192.168.1.2/24").to_json)
+ assert_equal("\"2001:200:300::1\"", IPAddr.new("2001:200:300::1").to_json)
+ assert_equal("\"2001:200:300::/48\"", IPAddr.new("2001:200:300::/48").to_json)
+ end
+
def test_netmask
a = IPAddr.new("192.168.1.2/8")
assert_equal(a.netmask, "255.0.0.0")