Skip to content

Commit 73bf325

Browse files
authored
Remove the unwanted #empty call on the collection (#524)
1 parent 496a2f9 commit 73bf325

File tree

2 files changed

+21
-5
lines changed

2 files changed

+21
-5
lines changed

lib/jbuilder/jbuilder_template.rb

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -141,9 +141,7 @@ def _render_partial_with_options(options)
141141
options.reverse_merge! ::JbuilderTemplate.template_lookup_options
142142
as = options[:as]
143143

144-
if options.key?(:collection) && (options[:collection].nil? || options[:collection].empty?)
145-
array!
146-
elsif as && options.key?(:collection) && CollectionRenderer.supported?
144+
if as && options.key?(:collection) && CollectionRenderer.supported?
147145
collection = options.delete(:collection) || []
148146
partial = options.delete(:partial)
149147
options[:locals].merge!(json: self)
@@ -156,9 +154,11 @@ def _render_partial_with_options(options)
156154
raise ::NotImplementedError, "The `:spacer_template' option is not supported in collection rendering."
157155
end
158156

159-
CollectionRenderer
157+
results = CollectionRenderer
160158
.new(@context.lookup_context, options) { |&block| _scope(&block) }
161159
.render_collection_with_partial(collection, partial, @context, nil)
160+
161+
array! if results.respond_to?(:body) && results.body.nil?
162162
elsif as && options.key?(:collection) && !CollectionRenderer.supported?
163163
# For Rails <= 5.2:
164164
as = as.to_sym

test/jbuilder_template_test.rb

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,22 @@ class JbuilderTemplateTest < ActiveSupport::TestCase
291291
assert_equal [], result
292292
end
293293

294+
test "works with an enumerable object" do
295+
enumerable_class = Class.new do
296+
include Enumerable
297+
alias length count # Rails 6.1 requires this.
298+
299+
def each(&block)
300+
[].each(&block)
301+
end
302+
end
303+
304+
result = render('json.array! @posts, partial: "post", as: :post, cached: true', posts: enumerable_class.new)
305+
306+
# Do not use #assert_empty as it is important to ensure that the type of the JSON result is an array.
307+
assert_equal [], result
308+
end
309+
294310
test "supports the cached: true option" do
295311
result = render('json.array! @posts, partial: "post", as: :post, cached: true', posts: POSTS)
296312

@@ -317,7 +333,7 @@ class JbuilderTemplateTest < ActiveSupport::TestCase
317333
assert_equal "Heinemeier Hansson", result[2]["author"]["last_name"]
318334
assert_equal "Pavel", result[5]["author"]["first_name"]
319335
end
320-
336+
321337
test "supports the cached: ->() {} option" do
322338
result = render('json.array! @posts, partial: "post", as: :post, cached: ->(post) { [post, "foo"] }', posts: POSTS)
323339

0 commit comments

Comments
 (0)