Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Handle empty top-level arrays (return "[]").

  • Loading branch information...
commit 133e4f11ffcf64a15486b3be23fb7042b95d7fe8 1 parent 6564a5b
@nragaz nragaz authored
Showing with 16 additions and 1 deletion.
  1. +4 −1 lib/jbuilder.rb
  2. +12 −0 test/jbuilder_test.rb
View
5 lib/jbuilder.rb
@@ -43,7 +43,8 @@ def child!
@attributes << _new_instance._tap { |jbuilder| yield jbuilder }.attributes!
end
- # Iterates over the passed collection and adds each iteration as an element of the resulting array.
+ # Turns the current element into an array and iterates over the passed collection, adding each iteration as
+ # an element of the resulting array.
#
# Example:
#
@@ -67,6 +68,8 @@ def child!
#
# { "people": [ { "David", 32 }, { "Jamie", 31 } ] }
def array!(collection)
+ @attributes = [] and return if collection.empty?
+
collection.each do |element|
child! do |child|
yield child, element
View
12 test/jbuilder_test.rb
@@ -193,6 +193,18 @@ def initialize(name, age)
end
end
+ test "empty top-level array" do
+ comments = []
+
+ json = Jbuilder.encode do |json|
+ json.array!(comments) do |json, comment|
+ json.content comment.content
+ end
+ end
+
+ assert_equal [], JSON.parse(json)
+ end
+
test "dynamically set a key/value" do
json = Jbuilder.encode do |json|
json.set!(:each, "stuff")
Please sign in to comment.
Something went wrong with that request. Please try again.