Skip to content

Commit cf8181d

Browse files
committed
Added to_json/as_json method
Updated to use cidr method when return address with prefix in #as_json
1 parent b4f366d commit cf8181d

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

lib/ipaddr.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,22 @@ def to_string
227227
return str
228228
end
229229

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+
230246
# Returns a string containing the IP address representation in
231247
# cidr notation
232248
def cidr

test/test_ipaddr.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,20 @@ def test_to_s
260260
assert_equal("3ffe:505:2::1", IPAddr.new("3ffe:505:2::1").to_s)
261261
end
262262

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+
263277
def test_netmask
264278
a = IPAddr.new("192.168.1.2/8")
265279
assert_equal(a.netmask, "255.0.0.0")

0 commit comments

Comments
 (0)