From c2b966cf653ea4264fbb008b8cc6ce5359ebe40a Mon Sep 17 00:00:00 2001 From: Yasuharu Ozaki Date: Wed, 24 Apr 2013 16:59:02 +0900 Subject: [PATCH 1/2] 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 = [] From 087b4225e244eba01ffa385f939bedf4fb429f80 Mon Sep 17 00:00:00 2001 From: Yasuharu Ozaki Date: Wed, 24 Apr 2013 17:04:58 +0900 Subject: [PATCH 2/2] Add usage about directly attribute from array --- README.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/README.md b/README.md index 8c2bd29..ba9059c 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,16 @@ end # => [ { "name": "David", "age": 32 }, { "name": "Jamie", "age": 31 } ] ``` +You can also extract attributes from array directly. + +``` ruby +# @people = People.all +json.array! @people :id :name + +# => [ { "id": 1, "name": "David" }, { "id": 2, "name": "Jamie" } ] +``` + + Jbuilder objects can be directly nested inside each other. Useful for composing objects. ``` ruby