Skip to content

Commit

Permalink
Fixed #to_json with prefix address
Browse files Browse the repository at this point in the history
  • Loading branch information
taketo1113 committed Dec 2, 2022
1 parent a126862 commit aa95b81
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 2 deletions.
5 changes: 5 additions & 0 deletions lib/ipaddr-ext.rb
@@ -1,4 +1,9 @@
require "ipaddr"
require 'json'

require "ipaddr-ext/version"
require "ipaddr-ext/extensions"
require "ipaddr-ext/json"

IPAddr.send(:include, IPAddrExt::Extensions)
IPAddr.send(:include, IPAddrExt::JSON)
2 changes: 0 additions & 2 deletions lib/ipaddr-ext/extensions.rb
@@ -1,7 +1,5 @@
# frozen_string_literal: true

require_relative "version"

module IPAddrExt
module Extensions
# Returns the broadcast address
Expand Down
15 changes: 15 additions & 0 deletions lib/ipaddr-ext/json.rb
@@ -0,0 +1,15 @@
# frozen_string_literal: true

module IPAddrExt
module JSON
def to_json
if ipv4? && prefix == 32
format("\"%s\"", to_s)
elsif ipv6? && prefix == 128
format("\"%s\"", to_s)
else
format("\"%s/%s\"", to_s, prefix)
end
end
end
end
17 changes: 17 additions & 0 deletions spec/ipaddr-ext/json_spec.rb
@@ -0,0 +1,17 @@
# frozen_string_literal: true

RSpec.describe IPAddrExt::JSON do
context "#to_json" do
it "ipv4" do
expect(IPAddr.new("192.168.1.1").to_json).to eq "\"192.168.1.1\""
expect(IPAddr.new("192.168.1.2/32").to_json).to eq "\"192.168.1.2\""
expect(IPAddr.new("192.168.1.0/24").to_json).to eq "\"192.168.1.0/24\""
end

it "ipv6" do
expect(IPAddr.new("3ffe:505:2::1").to_json).to eq "\"3ffe:505:2::1\""
expect(IPAddr.new("3ffe:505:2::2/128").to_json).to eq "\"3ffe:505:2::2\""
expect(IPAddr.new("3ffe:505:2::/64").to_json).to eq "\"3ffe:505:2::/64\""
end
end
end

0 comments on commit aa95b81

Please sign in to comment.