Skip to content

Commit

Permalink
Merge pull request rails#54314 from byroot/serialize-json-default
Browse files Browse the repository at this point in the history
Fix `serialize coder: JSON, type: Hash` to wrap the coder in `ColumnSerializer`
  • Loading branch information
byroot authored Jan 21, 2025
2 parents 44988c1 + bd24ca3 commit 568013e
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -220,10 +220,12 @@ def build_column_serializer(attr_name, coder, type, yaml = nil)
# to ensure special objects (e.g. Active Record models) are dumped correctly
# using the #as_json hook.

if coder == ::JSON || coder == Coders::JSON
coder = Coders::JSON.new
end

if coder == ::YAML || coder == Coders::YAMLColumn
Coders::YAMLColumn.new(attr_name, type, **(yaml || {}))
elsif coder == ::JSON || coder == Coders::JSON
Coders::JSON.new
elsif coder.respond_to?(:new) && !coder.respond_to?(:load)
coder.new(attr_name, type)
elsif type && type != Object
Expand Down
6 changes: 6 additions & 0 deletions activerecord/test/cases/serialized_attribute_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,12 @@ def test_json_read_db_null
assert_nil t.content
end

def test_json_type_hash_default_value
Topic.serialize :content, coder: JSON, type: Hash
t = Topic.new
assert_equal({}, t.content)
end

def test_json_symbolize_names_returns_symbolized_names
Topic.serialize :content, coder: ActiveRecord::Coders::JSON.new(symbolize_names: true)
my_post = posts(:welcome)
Expand Down

0 comments on commit 568013e

Please sign in to comment.