Skip to content

Commit

Permalink
Merge pull request #41931 from MarcelEeken/deep-merge-changing-origin…
Browse files Browse the repository at this point in the history
…al-hash

Deep duplicate in `deep_merge` so no references remain to the original hash in the result
  • Loading branch information
rafaelfranca committed Apr 12, 2021
1 parent 7261f90 commit 9f7d4ca
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 1 deletion.
6 changes: 6 additions & 0 deletions activesupport/CHANGELOG.md
@@ -1,5 +1,11 @@
* Fix issue in `Hash#deep_merge` where it did not properly duplicate a nested `Hash`

*Marcel Eeken*


## Rails 6.1.3.1 (March 26, 2021) ##


* No changes.


Expand Down
Expand Up @@ -16,7 +16,7 @@ class Hash
# h1.deep_merge(h2) { |key, this_val, other_val| this_val + other_val }
# # => { a: 100, b: 450, c: { c1: 300 } }
def deep_merge(other_hash, &block)
dup.deep_merge!(other_hash, &block)
deep_dup.deep_merge!(other_hash, &block)
end

# Same as +deep_merge+, but modifies +self+.
Expand Down
10 changes: 10 additions & 0 deletions activesupport/test/core_ext/hash_ext_test.rb
Expand Up @@ -300,6 +300,16 @@ def test_deep_merge_with_falsey_values
assert_equal expected, hash_1
end

def test_deep_merge_with_nested_hash_returning_full_new_hash
hash_1 = { a: { b: "foo" } }
hash_2 = { d: "bar" }

new_hash = hash_1.deep_merge(hash_2)
new_hash[:a][:b] = "baz"

assert_equal("foo", hash_1[:a][:b])
end

def test_reverse_merge
defaults = { d: 0, a: "x", b: "y", c: 10 }.freeze
options = { a: 1, b: 2 }
Expand Down

0 comments on commit 9f7d4ca

Please sign in to comment.