Skip to content

Commit

Permalink
Merge pull request #47273 from hahmed/ha/fix-as_json-for-data-object
Browse files Browse the repository at this point in the history
Fixes encoding/decoding Data object via as_json
  • Loading branch information
guilleiguaran committed Feb 7, 2023
2 parents 20bcd41 + 52bc74b commit 89a2608
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
8 changes: 8 additions & 0 deletions activesupport/lib/active_support/core_ext/object/json.rb
Expand Up @@ -65,6 +65,14 @@ def as_json(options = nil) # :nodoc:
end
end

if RUBY_VERSION >= "3.2"
class Data # :nodoc:
def as_json(options = nil)
Hash[members.zip(deconstruct)].as_json(options)
end
end
end

class Struct # :nodoc:
def as_json(options = nil)
Hash[members.zip(values)].as_json(options)
Expand Down
11 changes: 11 additions & 0 deletions activesupport/test/json/encoding_test.rb
Expand Up @@ -334,6 +334,17 @@ def test_struct_encoding
ActiveSupport::JSON.decode(json_string_and_date))
end

if RUBY_VERSION >= "3.2"
def test_data_encoding
data = Data.define(:name, :email).new("test", "test@example.com")

assert_nothing_raised { data.to_json }

assert_equal({ "name" => "test", "email" => "test@example.com" },
ActiveSupport::JSON.decode(data.to_json))
end
end

def test_nil_true_and_false_represented_as_themselves
assert_nil nil.as_json
assert_equal true, true.as_json
Expand Down

0 comments on commit 89a2608

Please sign in to comment.