Method: Jbuilder#array!
- Defined in:
- lib/jbuilder.rb
#array!(collection = [], *attributes) ⇒ Object
Turns the current element into an array and iterates over the passed collection, adding each iteration as an element of the resulting array.
Example:
json.array!(@people) do |person|
json.name person.name
json.age calculate_age(person.birthday)
end
[ { "name": David", "age": 32 }, { "name": Jamie", "age": 31 } ]
If you are using Ruby 1.9+, you can use the call syntax instead of an explicit extract! call:
json.(@people) { |person| ... }
It’s generally only needed to use this method for top-level arrays. If you have named arrays, you can do:
json.people(@people) do |person|
json.name person.name
json.age calculate_age(person.birthday)
end
{ "people": [ { "name": David", "age": 32 }, { "name": Jamie", "age": 31 } ] }
If you omit the block then you can set the top level array directly:
json.array! [1, 2, 3]
[1,2,3]
184 185 186 187 188 189 190 191 192 193 194 195 196 |
# File 'lib/jbuilder.rb', line 184 def array!(collection = [], *attributes) array = if collection.nil? [] elsif ::Kernel.block_given? _map_collection(collection, &::Proc.new) elsif attributes.any? _map_collection(collection) { |element| extract! element, *attributes } else collection.to_a end merge! array end |