Skip to content

Commit 5e0aa27

Browse files
Deep-merge nested hashes
1 parent e5f57cf commit 5e0aa27

File tree

3 files changed

+22
-1
lines changed

3 files changed

+22
-1
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ Unreleased
44
----------
55

66
* Requires Rails 5+ and Ruby 2.2+
7+
* Nested hashes are deep-merged
78

89
2.9.1
910
-----

lib/jbuilder.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -275,7 +275,7 @@ def _merge_values(current_value, updates)
275275
elsif ::Array === current_value && ::Array === updates
276276
current_value + updates
277277
elsif ::Hash === current_value && ::Hash === updates
278-
current_value.merge(updates)
278+
current_value.deep_merge(updates)
279279
else
280280
raise MergeError.build(current_value, updates)
281281
end

test/jbuilder_test.rb

+20
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
require 'test_helper'
22
require 'active_support/inflector'
3+
require 'active_support/core_ext/hash/deep_merge'
34
require 'jbuilder'
45

56
def jbuild(*args, &block)
@@ -159,6 +160,25 @@ class JbuilderTest < ActiveSupport::TestCase
159160
assert_equal 32, result['author']['age']
160161
end
161162

163+
test 'nested blocks are additive' do
164+
result = jbuild do |json|
165+
json.author do
166+
json.name do
167+
json.first 'David'
168+
end
169+
end
170+
171+
json.author do
172+
json.name do
173+
json.last 'Heinemeier Hansson'
174+
end
175+
end
176+
end
177+
178+
assert_equal 'David', result['author']['name']['first']
179+
assert_equal 'Heinemeier Hansson', result['author']['name']['last']
180+
end
181+
162182
test 'support merge! method' do
163183
result = jbuild do |json|
164184
json.merge! 'foo' => 'bar'

0 commit comments

Comments
 (0)