Skip to content

Commit

Permalink
Merge pull request #37919 from joelhawksley/controller-render-in
Browse files Browse the repository at this point in the history
Render objects that respond_to render_in in controllers
  • Loading branch information
eileencodes committed Dec 10, 2019
2 parents 836fbf2 + 20a83f5 commit e36097a
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 0 deletions.
10 changes: 10 additions & 0 deletions actionpack/test/controller/renderer_test.rb
@@ -1,6 +1,7 @@
# frozen_string_literal: true

require "abstract_unit"
require "test_component"

class RendererTest < ActiveSupport::TestCase
test "action controller base has a renderer" do
Expand Down Expand Up @@ -65,6 +66,15 @@ class RendererTest < ActiveSupport::TestCase
assert_equal "The secret is foo\n", content
end

def test_render_component
renderer = ApplicationController.renderer

assert_equal(
%(<span title="my title">(Inline render)</span>),
renderer.render(TestComponent.new(title: "my title")).strip
)
end

test "rendering with custom env" do
renderer = ApplicationController.renderer.new method: "post"
content = renderer.render inline: "<%= request.post? %>"
Expand Down
45 changes: 45 additions & 0 deletions actionpack/test/lib/test_component.rb
@@ -0,0 +1,45 @@
# frozen_string_literal: true

class TestComponent < ActionView::Base
include ActiveModel::Validations

validates :title, presence: true
delegate :render, to: :view_context

def initialize(title:)
@title = title
end

def render_in(view_context)
self.class.compile
@view_context = view_context
validate!
rendered_template
end

def format
:html
end

def self.template
<<~'erb'
<span title="<%= title %>">(<%= render(plain: "Inline render") %>)</span>
erb
end

def self.compile
@compiled ||= nil
return if @compiled

class_eval(
"def rendered_template; @output_buffer = ActionView::OutputBuffer.new; " +
ActionView::Template::Handlers::ERB.erb_implementation.new(template, trim: true).src +
"; end"
)

@compiled = true
end

private
attr_reader :title, :view_context
end
3 changes: 3 additions & 0 deletions actionview/lib/action_view/renderer/renderer.rb
Expand Up @@ -25,6 +25,9 @@ def render(context, options)
def render_to_object(context, options) # :nodoc:
if options.key?(:partial)
render_partial_to_object(context, options)
elsif options.key?(:object)
object = options[:object]
AbstractRenderer::RenderedTemplate.new(object.render_in(context), object)
else
render_template_to_object(context, options)
end
Expand Down
2 changes: 2 additions & 0 deletions actionview/lib/action_view/rendering.rb
Expand Up @@ -144,6 +144,8 @@ def _normalize_args(action = nil, options = {})
else
if action.respond_to?(:permitted?) && action.permitted?
options = action
elsif action.respond_to?(:render_in)
options[:object] = action
else
options[:partial] = action
end
Expand Down

0 comments on commit e36097a

Please sign in to comment.