Skip to content

Commit

Permalink
Remove the unwanted #empty call on the collection (#524)
Browse files Browse the repository at this point in the history
  • Loading branch information
yuki24 authored Dec 17, 2021
1 parent 496a2f9 commit 73bf325
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
8 changes: 4 additions & 4 deletions lib/jbuilder/jbuilder_template.rb
Original file line number Diff line number Diff line change
Expand Up @@ -141,9 +141,7 @@ def _render_partial_with_options(options)
options.reverse_merge! ::JbuilderTemplate.template_lookup_options
as = options[:as]

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

CollectionRenderer
results = CollectionRenderer
.new(@context.lookup_context, options) { |&block| _scope(&block) }
.render_collection_with_partial(collection, partial, @context, nil)

array! if results.respond_to?(:body) && results.body.nil?
elsif as && options.key?(:collection) && !CollectionRenderer.supported?
# For Rails <= 5.2:
as = as.to_sym
Expand Down
18 changes: 17 additions & 1 deletion test/jbuilder_template_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,22 @@ class JbuilderTemplateTest < ActiveSupport::TestCase
assert_equal [], result
end

test "works with an enumerable object" do
enumerable_class = Class.new do
include Enumerable
alias length count # Rails 6.1 requires this.

def each(&block)
[].each(&block)
end
end

result = render('json.array! @posts, partial: "post", as: :post, cached: true', posts: enumerable_class.new)

# Do not use #assert_empty as it is important to ensure that the type of the JSON result is an array.
assert_equal [], result
end

test "supports the cached: true option" do
result = render('json.array! @posts, partial: "post", as: :post, cached: true', posts: POSTS)

Expand All @@ -317,7 +333,7 @@ class JbuilderTemplateTest < ActiveSupport::TestCase
assert_equal "Heinemeier Hansson", result[2]["author"]["last_name"]
assert_equal "Pavel", result[5]["author"]["first_name"]
end

test "supports the cached: ->() {} option" do
result = render('json.array! @posts, partial: "post", as: :post, cached: ->(post) { [post, "foo"] }', posts: POSTS)

Expand Down

0 comments on commit 73bf325

Please sign in to comment.