Skip to content

Commit

Permalink
Don't stringify return values from jb templates
Browse files Browse the repository at this point in the history
Rails 7.1 calls to_s against all templates' return value since rails/rails@ee68644,
and this incompatibility broke jb templates that return non-String objects, e.g. Hash or Array.
This monkey-patch redefines to_s method on such objects not to stringify themselves.

fixes #43
  • Loading branch information
amatsuda committed Sep 16, 2023
1 parent 8e99098 commit fb4b0de
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions lib/jb/action_view_monkeys.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,19 @@ def render_template(_view, template, *)
end
end

# Rails 7.1+: A monkey-patch not to stringify rendered object from JB templates
module BaseToSCanceller
def _run(method, template, *, **)
val = super
if template.respond_to?(:handler) && (template.handler == Jb::Handler)
def val.to_s
self
end
end
val
end
end

# Rails 6.1+: A monkey-patch for jb template collection result's `body` not to return a String but an Array
module CollectionRendererExtension
private def render_collection(_collection, _view, _path, template, _layout, _block)
Expand Down Expand Up @@ -45,6 +58,7 @@ def obj.body; @rendered_templates.map(&:body); end
end

::ActionView::TemplateRenderer.prepend ::Jb::TemplateRenderer::JSONizer
::ActionView::Base.prepend ::Jb::BaseToSCanceller
begin
# ActionView::CollectionRenderer is a newly added class since 6.1
::ActionView::CollectionRenderer.prepend ::Jb::CollectionRendererExtension
Expand Down

0 comments on commit fb4b0de

Please sign in to comment.