Skip to content
Merged
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
16 changes: 16 additions & 0 deletions lib/ipaddr.rb
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,22 @@ def to_string
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)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was your intent as_json(*args) because you gave it a name?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@knu It is not necessary a name. I have removed a name of args.
It is from another patch which is ruby/json@f1ffc4a

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I prefer the implementation of to_json to be as_json.to_json(*args) so it is easier to change how IPAddrs are encoded simply by overriding as_json. With the current definition, when you want it to be def as_json(*) = to_f you'll need to rewrite to_json as well.

end

# Returns a string containing the IP address representation in
# cidr notation
def cidr
Expand Down
14 changes: 14 additions & 0 deletions test/test_ipaddr.rb
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,20 @@ def test_to_s
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")
Expand Down