Allow template to return any kind of objects

Fix: https://github.com/rails/rails/issues/50930

While Action View is predominantly meant to render text,
in sime case it's used to render more complex object.

So we shouldn't assume `#_run` returns a buffer.
This commit is contained in:
Jean Boussier 2024-02-09 14:52:16 +01:00
parent f5ea4a5260
commit f62ff52c65
2 changed files with 10 additions and 1 deletions

View File

@ -272,7 +272,8 @@ module ActionView
view._run(method_name, self, locals, buffer, add_to_stack: add_to_stack, has_strict_locals: strict_locals?, &block)
nil
else
view._run(method_name, self, locals, OutputBuffer.new, add_to_stack: add_to_stack, has_strict_locals: strict_locals?, &block)&.to_s
result = view._run(method_name, self, locals, OutputBuffer.new, add_to_stack: add_to_stack, has_strict_locals: strict_locals?, &block)
result.is_a?(OutputBuffer) ? result.to_s : result
end
end
rescue => e

View File

@ -121,6 +121,14 @@ class TestERBTemplate < ActiveSupport::TestCase
assert_equal "hellopartialhello", render
end
def test_rendering_non_string
my_object = Object.new
eval_handler = ->(_template, source) { source }
@template = ActionView::Template.new("my_object", "__id__", eval_handler, virtual_path: "hello", locals: [:my_object])
result = render(my_object: my_object)
assert_same my_object, result
end
def test_resulting_string_is_utf8
@template = new_template
assert_equal Encoding::UTF_8, render.encoding