Skip to content

Commit

Permalink
Allow quick extract attributes from array
Browse files Browse the repository at this point in the history
  • Loading branch information
yasuoza committed Apr 24, 2013
1 parent cc52e66 commit c2b966c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
6 changes: 4 additions & 2 deletions lib/jbuilder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -224,8 +224,10 @@ def child!
# json.array! [1, 2, 3]
#
# [1,2,3]
def array!(collection, &block)
@attributes = if ::Kernel::block_given?
def array!(collection, *attributes, &block)
@attributes = if attributes.present?
_map_collection(collection) { |element| extract!(element, *attributes) }
elsif ::Kernel::block_given?
_map_collection(collection) { |element| block.arity == 2 ? block[self, element] : block[element] }
else
collection
Expand Down
14 changes: 14 additions & 0 deletions test/jbuilder_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,20 @@ def initialize(name, age)
assert_equal 'world', parsed.second['content']
end

test 'extract attributes directly from array' do
comments = [ Comment.new('hello', 1), Comment.new('world', 2) ]

json = Jbuilder.encode do |json|
json.array! comments, :content, :id
end

parsed = MultiJson.load(json)
assert_equal 'hello', parsed.first['content']
assert_equal 1, parsed.first['id']
assert_equal 'world', parsed.second['content']
assert_equal 2, parsed.second['id']
end

test 'empty top-level array' do
comments = []

Expand Down

0 comments on commit c2b966c

Please sign in to comment.