Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/jbuilder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
28 changes: 28 additions & 0 deletions test/jbuilder_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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 = []

Expand Down