From 469a53081f8e2f23f9c824ce992c4f574b294d70 Mon Sep 17 00:00:00 2001 From: Peter Zhu Date: Fri, 22 Jan 2021 10:51:36 -0500 Subject: [PATCH] Allow Jbuilder instance in merge! (#485) --- lib/jbuilder.rb | 11 +++++++++-- test/jbuilder_test.rb | 12 ++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/lib/jbuilder.rb b/lib/jbuilder.rb index ee128db..defd55e 100644 --- a/lib/jbuilder.rb +++ b/lib/jbuilder.rb @@ -241,8 +241,15 @@ def attributes! @attributes end - # Merges hash or array into current builder. - def merge!(hash_or_array) + # Merges hash, array, or Jbuilder instance into current builder. + def merge!(obj) + hash_or_array = + if ::Jbuilder === obj + obj.attributes! + else + obj + end + @attributes = _merge_values(@attributes, hash_or_array) end diff --git a/test/jbuilder_test.rb b/test/jbuilder_test.rb index c0eb847..5f46ea8 100644 --- a/test/jbuilder_test.rb +++ b/test/jbuilder_test.rb @@ -196,6 +196,18 @@ class JbuilderTest < ActiveSupport::TestCase assert_equal 'Pavel', result['author']['name'] end + test 'support merge! method with Jbuilder instance' do + obj = jbuild do |json| + json.foo 'bar' + end + + result = jbuild do |json| + json.merge! obj + end + + assert_equal 'bar', result['foo'] + end + test 'blocks are additive via extract syntax' do person = Person.new('Pavel', 27)