Skip to content

Commit e7d207f

Browse files
committed
Change IPAddr#to_json to match the behavior of the json gem
Returning the string representation instead of the instance variables of the object. Before: ```ruby IPAddr.new("127.0.0.1").to_json # => "{\"addr\":2130706433,\"family\":2,\"mask_addr\":4294967295}" ``` After: ```ruby IPAddr.new("127.0.0.1").to_json # => "\"127.0.0.1\"" ``` Fixes rails#40932.
1 parent 68b471c commit e7d207f

File tree

2 files changed

+9
-0
lines changed

2 files changed

+9
-0
lines changed

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
# Hack to load json gem first so we can overwrite its to_json.
44
require "json"
55
require "bigdecimal"
6+
require "ipaddr"
67
require "uri/generic"
78
require "pathname"
89
require "active_support/core_ext/big_decimal/conversions" # for #to_s
@@ -219,6 +220,12 @@ def as_json(options = nil)
219220
end
220221
end
221222

223+
class IPAddr # :nodoc:
224+
def as_json(options = nil)
225+
to_s
226+
end
227+
end
228+
222229
class Process::Status #:nodoc:
223230
def as_json(options = nil)
224231
{ exitstatus: exitstatus, pid: pid }

activesupport/test/json/encoding_test_cases.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,8 @@ module EncodingTestCases
8686

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

89+
IPAddrTests = [[ IPAddr.new("127.0.0.1"), %("127.0.0.1") ]]
90+
8991
DateTests = [[ Date.new(2005, 2, 1), %("2005/02/01") ]]
9092
TimeTests = [[ Time.utc(2005, 2, 1, 15, 15, 10), %("2005/02/01 15:15:10 +0000") ]]
9193
DateTimeTests = [[ DateTime.civil(2005, 2, 1, 15, 15, 10), %("2005/02/01 15:15:10 +0000") ]]

0 commit comments

Comments
 (0)