Skip to content

Commit

Permalink
Change IPAddr#to_json to match the behavior of the json gem
Browse files Browse the repository at this point in the history
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 #40932.
  • Loading branch information
rafaelfranca committed Dec 28, 2020
1 parent 276961b commit 4bbfc87
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
18 changes: 18 additions & 0 deletions activesupport/CHANGELOG.md
@@ -1,3 +1,21 @@
* 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\""
```


## Rails 6.1.0 (December 09, 2020) ##

* Ensure `MemoryStore` disables compression by default. Reverts behavior of
Expand Down
7 changes: 7 additions & 0 deletions activesupport/lib/active_support/core_ext/object/json.rb
Expand Up @@ -3,6 +3,7 @@
# Hack to load json gem first so we can overwrite its to_json.
require "json"
require "bigdecimal"
require "ipaddr"
require "uri/generic"
require "pathname"
require "active_support/core_ext/big_decimal/conversions" # for #to_s
Expand Down Expand Up @@ -219,6 +220,12 @@ def as_json(options = nil)
end
end

class IPAddr # :nodoc:
def as_json(options = nil)
to_s
end
end

class Process::Status #:nodoc:
def as_json(options = nil)
{ exitstatus: exitstatus, pid: pid }
Expand Down
2 changes: 2 additions & 0 deletions activesupport/test/json/encoding_test_cases.rb
Expand Up @@ -86,6 +86,8 @@ module EncodingTestCases

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

IPAddrTests = [[ IPAddr.new("127.0.0.1"), %("127.0.0.1") ]]

DateTests = [[ Date.new(2005, 2, 1), %("2005/02/01") ]]
TimeTests = [[ Time.utc(2005, 2, 1, 15, 15, 10), %("2005/02/01 15:15:10 +0000") ]]
DateTimeTests = [[ DateTime.civil(2005, 2, 1, 15, 15, 10), %("2005/02/01 15:15:10 +0000") ]]
Expand Down

0 comments on commit 4bbfc87

Please sign in to comment.