Skip to content

Commit

Permalink
Fix Jbuilder#merge! inside block
Browse files Browse the repository at this point in the history
  • Loading branch information
rwz committed Oct 8, 2014
1 parent a215234 commit a7b3285
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 19 deletions.
32 changes: 13 additions & 19 deletions lib/jbuilder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -255,18 +255,25 @@ def _extract_method_values(object, *attributes)
def _merge_block(key, &block)
current_value = _blank? ? BLANK : @attributes.fetch(_key(key), BLANK)
raise NullError.build(key) if current_value.nil?
new_value = _scope{ yield self }
_merge_values(current_value, new_value)
end

value = _scope{ yield self }

if _blank?(value)
def _merge_values(current_value, updates)
if _blank?(updates)
current_value
elsif _blank?(current_value) || value.nil?
value
elsif _blank?(current_value) || updates.nil?
updates
elsif ::Array === updates
current_value = ::Array === current_value ? current_value.dup : []
current_value.concat updates
else
_merge_values(current_value, value)
current_value = current_value.dup
current_value.update updates
end
end


def _write(key, value)
@attributes = {} if _blank?
@attributes[_key(key)] = value
Expand Down Expand Up @@ -302,19 +309,6 @@ def _mapable_arguments?(value, *args)
value.respond_to?(:map)
end

def _merge_values(attributes, hash_or_array)
attributes = attributes.dup

if ::Array === hash_or_array
attributes = [] unless ::Array === attributes
attributes.concat hash_or_array
else
attributes.update hash_or_array
end

attributes
end

def _blank?(value=@attributes)
BLANK == value
end
Expand Down
18 changes: 18 additions & 0 deletions test/jbuilder_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,24 @@ class JbuilderTest < ActiveSupport::TestCase
assert_equal 32, result['author']['age']
end

test 'support merge! method' do
result = jbuild do |json|
json.merge! 'foo' => 'bar'
end

assert_equal 'bar', result['foo']
end

test 'support merge! method in a block' do
result = jbuild do |json|
json.author do
json.merge! 'name' => 'Pavel'
end
end

assert_equal 'Pavel', result['author']['name']
end

test 'blocks are additive via extract syntax' do
person = Person.new('Pavel', 27)

Expand Down

0 comments on commit a7b3285

Please sign in to comment.