Skip to content

Commit

Permalink
Merge pull request #129 from YasuOza/direct_attributes_from_array
Browse files Browse the repository at this point in the history
Direct attributes from array
  • Loading branch information
rwz committed Apr 24, 2013
2 parents cc52e66 + 087b422 commit 749cf6b
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
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 749cf6b

Please sign in to comment.