Skip to content

Commit 546ca81

Browse files
authored
Merge pull request rails#53393 from taketo1113/fix-json-ipaddr2
Add prefix address when IPAddr of CIDR encoded with JSON
2 parents d4fff28 + a11e7c2 commit 546ca81

File tree

3 files changed

+30
-4
lines changed

3 files changed

+30
-4
lines changed

activesupport/CHANGELOG.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,17 @@
1+
* `ActiveSupport::JSON.encode` supports CIDR notation.
2+
3+
Previously:
4+
5+
```ruby
6+
ActiveSupport::JSON.encode(IPAddr.new("172.16.0.0/24")) # => "\"172.16.0.0\""
7+
```
8+
9+
After this change:
10+
11+
```ruby
12+
ActiveSupport::JSON.encode(IPAddr.new("172.16.0.0/24")) # => "\"172.16.0.0/24\""
13+
```
14+
15+
*Taketo Takashima*
116

217
Please check [8-0-stable](https://github.com/rails/rails/blob/8-0-stable/activesupport/CHANGELOG.md) for previous changes.

activesupport/lib/active_support/core_ext/object/json.rb

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -239,9 +239,18 @@ def as_json(options = nil)
239239
end
240240
end
241241

242-
class IPAddr # :nodoc:
243-
def as_json(options = nil)
244-
to_s
242+
unless IPAddr.method_defined?(:as_json, false)
243+
# Use `IPAddr#as_json` from the IPAddr gem if the version is 1.2.7 or higher.
244+
class IPAddr # :nodoc:
245+
def as_json(options = nil)
246+
if ipv4? && prefix == 32
247+
to_s
248+
elsif ipv6? && prefix == 128
249+
to_s
250+
else
251+
"#{self}/#{prefix}"
252+
end
253+
end
245254
end
246255
end
247256

activesupport/test/json/encoding_test_cases.rb

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,9 @@ module EncodingTestCases
113113

114114
PathnameTests = [[ Pathname.new("lib/index.rb"), %("lib/index.rb") ]]
115115

116-
IPAddrTests = [[ IPAddr.new("127.0.0.1"), %("127.0.0.1") ]]
116+
IPAddrTests = [[ IPAddr.new("127.0.0.1"), %("127.0.0.1") ]]
117+
IPAddrv4CidrTests = [[ IPAddr.new("192.0.2.0/24"), %("192.0.2.0/24") ]]
118+
IPAddrv6CidrTests = [[ IPAddr.new("2001:db8::/48"), %("2001:db8::/48") ]]
117119

118120
DateTests = [[ Date.new(2005, 2, 1), %("2005/02/01") ]]
119121
TimeTests = [[ Time.utc(2005, 2, 1, 15, 15, 10), %("2005/02/01 15:15:10 +0000") ]]

0 commit comments

Comments
 (0)