File tree Expand file tree Collapse file tree 2 files changed +30
-0
lines changed Expand file tree Collapse file tree 2 files changed +30
-0
lines changed Original file line number Diff line number Diff line change @@ -227,6 +227,22 @@ def to_string
227
227
return str
228
228
end
229
229
230
+ # Returns a string containing the IP address representation with prefix.
231
+ def as_json ( *)
232
+ if ipv4? && prefix == 32
233
+ to_s
234
+ elsif ipv6? && prefix == 128
235
+ to_s
236
+ else
237
+ cidr
238
+ end
239
+ end
240
+
241
+ # Returns a json string containing the IP address representation.
242
+ def to_json ( *)
243
+ format ( "\" %s\" " , as_json )
244
+ end
245
+
230
246
# Returns a string containing the IP address representation in
231
247
# cidr notation
232
248
def cidr
Original file line number Diff line number Diff line change @@ -260,6 +260,20 @@ def test_to_s
260
260
assert_equal ( "3ffe:505:2::1" , IPAddr . new ( "3ffe:505:2::1" ) . to_s )
261
261
end
262
262
263
+ def test_as_json
264
+ assert_equal ( "192.168.1.2" , IPAddr . new ( "192.168.1.2" ) . as_json )
265
+ assert_equal ( "192.168.1.0/24" , IPAddr . new ( "192.168.1.2/24" ) . as_json )
266
+ assert_equal ( "2001:200:300::1" , IPAddr . new ( "2001:200:300::1" ) . as_json )
267
+ assert_equal ( "2001:200:300::/48" , IPAddr . new ( "2001:200:300::/48" ) . as_json )
268
+ end
269
+
270
+ def test_to_json
271
+ assert_equal ( "\" 192.168.1.2\" " , IPAddr . new ( "192.168.1.2" ) . to_json )
272
+ assert_equal ( "\" 192.168.1.0/24\" " , IPAddr . new ( "192.168.1.2/24" ) . to_json )
273
+ assert_equal ( "\" 2001:200:300::1\" " , IPAddr . new ( "2001:200:300::1" ) . to_json )
274
+ assert_equal ( "\" 2001:200:300::/48\" " , IPAddr . new ( "2001:200:300::/48" ) . to_json )
275
+ end
276
+
263
277
def test_netmask
264
278
a = IPAddr . new ( "192.168.1.2/8" )
265
279
assert_equal ( a . netmask , "255.0.0.0" )
You can’t perform that action at this time.
0 commit comments