From c2b966cf653ea4264fbb008b8cc6ce5359ebe40a Mon Sep 17 00:00:00 2001 From: Yasuharu Ozaki Date: Wed, 24 Apr 2013 16:59:02 +0900 Subject: [PATCH] Allow quick extract attributes from array --- lib/jbuilder.rb | 6 ++++-- test/jbuilder_test.rb | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/lib/jbuilder.rb b/lib/jbuilder.rb index f96bc99..ffece0e 100644 --- a/lib/jbuilder.rb +++ b/lib/jbuilder.rb @@ -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 diff --git a/test/jbuilder_test.rb b/test/jbuilder_test.rb index 9923d81..1754d9f 100644 --- a/test/jbuilder_test.rb +++ b/test/jbuilder_test.rb @@ -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 = []