Skip to content

Commit

Permalink
ActiveRecord::Store encode store as a regular Hash
Browse files Browse the repository at this point in the history
Fix: rails#45585

There's no benefit in serializing it as HWIA, it requires
to allow that type for YAML safe_load and takes more space.

We can cast it back to a regular hash before serialization.
  • Loading branch information
byroot committed Jul 13, 2022
1 parent 84555af commit 05fdb3e
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 20 deletions.
7 changes: 7 additions & 0 deletions activerecord/CHANGELOG.md
@@ -1,3 +1,10 @@
* Fix `ActiveRecord::Store` to serialize as a regular Hash

Previously it would serialize as an `ActiveSupport::HashWithIndifferentAccess`
which is wasteful and cause problem with YAML safe_load.

*Jean Boussier*

* Add `timestamptz` as a time zone aware type for PostgreSQL

This is required for correctly parsing `timestamp with time zone` values in your database.
Expand Down
14 changes: 13 additions & 1 deletion activerecord/lib/active_record/store.rb
Expand Up @@ -268,7 +268,7 @@ def initialize(attr_name, coder_or_class_name)
end

def dump(obj)
@coder.dump self.class.as_indifferent_hash(obj)
@coder.dump as_regular_hash(obj)
end

def load(yaml)
Expand All @@ -285,6 +285,18 @@ def self.as_indifferent_hash(obj)
ActiveSupport::HashWithIndifferentAccess.new
end
end

private
def as_regular_hash(obj)
case obj
when ActiveSupport::HashWithIndifferentAccess
obj.to_h
when Hash
obj
else
{}
end
end
end
end
end
19 changes: 0 additions & 19 deletions activerecord/test/cases/store_test.rb
Expand Up @@ -16,7 +16,6 @@ class StoreTest < ActiveRecord::TestCase
parent_name: "Quinn", partner_name: "Dallas",
partner_birthday: "1997-11-1"
)
ActiveRecord.use_yaml_unsafe_load = true
end

test "reading store attributes through accessors" do
Expand Down Expand Up @@ -321,21 +320,3 @@ def test_convert_store_attributes_from_Hash_to_HashWithIndifferentAccess_saving_
assert_equal [:secret_question, :two_factor_auth, :login_retry], Admin::User.stored_attributes[:configs]
end
end

class StoreTestWithYAMLSafeLoad < StoreTest
fixtures :'admin/users'

setup do
@john = Admin::UserJSON.create!(
name: "Jim Doe", color: "black", remember_login: true,
height: "tall", is_a_good_guy: true,
parent_name: "Quinn", partner_name: "Dallas",
partner_birthday: "1997-11-1"
)
ActiveRecord.use_yaml_unsafe_load = false
end

def test_convert_store_attributes_from_Hash_to_HashWithIndifferentAccess_saving_the_data_and_access_attributes_indifferently
skip "Symbol is not a supported class in Psych::safe_load"
end
end

0 comments on commit 05fdb3e

Please sign in to comment.