Skip to content

Commit

Permalink
Cast collection to array before merge
Browse files Browse the repository at this point in the history
Fix #205
  • Loading branch information
rwz committed Jul 7, 2014
1 parent ca1a95b commit 7b8c8a1
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
8 changes: 4 additions & 4 deletions lib/jbuilder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -174,12 +174,14 @@ def child!
#
# [1,2,3]
def array!(collection = [], *attributes, &block)
array = if block
array = if collection.nil?
[]
elsif block
_map_collection(collection, &block)
elsif attributes.any?
_map_collection(collection) { |element| extract! element, *attributes }
else
collection
collection.to_a
end

merge! array
Expand Down Expand Up @@ -276,8 +278,6 @@ def _set_value(key, value)
end

def _map_collection(collection)
return [] if collection.nil?

collection.map do |element|
_scope{ yield element }
end
Expand Down
20 changes: 20 additions & 0 deletions test/jbuilder_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,16 @@ def map(&block)
end
end

class VeryBasicWrapper < BasicObject
def initialize(thing)
@thing = thing
end

def method_missing(name, *args, &block)
@thing.send name, *args, &block
end
end

# This is not Struct, because structs are Enumerable
class Person
attr_reader :name, :age
Expand Down Expand Up @@ -254,6 +264,16 @@ class JbuilderTest < ActiveSupport::TestCase
assert_equal 'world', result['comments'].second['content']
end

test 'array! casts array-like objects to array before merging' do
wrapped_array = VeryBasicWrapper.new(%w[foo bar])

result = jbuild do |json|
json.array! wrapped_array
end

assert_equal %w[foo bar], result
end

test 'nesting multiple children from array with inline loop on root' do
comments = [ Comment.new('hello', 1), Comment.new('world', 2) ]

Expand Down

0 comments on commit 7b8c8a1

Please sign in to comment.