diff --git a/lib/jbuilder.rb b/lib/jbuilder.rb index 0edab64..5e48431 100644 --- a/lib/jbuilder.rb +++ b/lib/jbuilder.rb @@ -254,7 +254,7 @@ def target! private def _extract_hash_values(object, attributes) - attributes.each{ |key| _set_value key, object.fetch(key) } + attributes.each{ |key| _set_value key, object.fetch(key, BLANK) } end def _extract_method_values(object, attributes) diff --git a/test/jbuilder_test.rb b/test/jbuilder_test.rb index 18766a1..f8ac43f 100644 --- a/test/jbuilder_test.rb +++ b/test/jbuilder_test.rb @@ -450,6 +450,34 @@ class JbuilderTest < ActiveSupport::TestCase assert_equal 2, result.second['id'] end + test 'extract hash keys directly from array' do + comments = [ { content: 'hello', id: 1 }, { content: 'world', id: 2 } ] + + result = jbuild do |json| + json.array! comments, :content, :id + end + + assert_equal 'hello', result.first['content'] + assert_equal 1, result.first['id'] + assert_equal 'world', result.second['content'] + assert_equal 2, result.second['id'] + end + + test 'missing hash keys ' do + comments = [ { content: 'hello', id: 1, meta: 'meta' }, { content: 'world', id: 2 } ] + + result = jbuild do |json| + json.array! comments, :content, :id, :meta + end + + assert_equal 'hello', result.first['content'] + assert_equal 1, result.first['id'] + assert_equal 'meta', result.first['meta'] + assert_equal 'world', result.second['content'] + assert_equal 2, result.second['id'] + assert_nil result.second['meta'] + end + test 'empty top-level array' do comments = []