diff --git a/lib/jbuilder/jbuilder_template.rb b/lib/jbuilder/jbuilder_template.rb index 8a8c970..2b90d74 100644 --- a/lib/jbuilder/jbuilder_template.rb +++ b/lib/jbuilder/jbuilder_template.rb @@ -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) @@ -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 diff --git a/test/jbuilder_template_test.rb b/test/jbuilder_template_test.rb index 5ff3a79..eaac505 100644 --- a/test/jbuilder_template_test.rb +++ b/test/jbuilder_template_test.rb @@ -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) @@ -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)