aboutsummaryrefslogtreecommitdiffstats
path: root/actionview/test/lib/test_component.rb
blob: 0d45d6e25f91303e78fdc9193559b260837ad4c5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# frozen_string_literal: true

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

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

  def initialize(title:)
    @title = title
  end

  # Entrypoint for rendering. Called by ActionView::RenderingHelper#render.
  #
  # Returns ActionView::OutputBuffer.
  def render_in(view_context, &block)
    self.class.compile
    @view_context = view_context
    @content = view_context.capture(&block) if block_given?
    validate!
    rendered_template
  end

  def self.template
    <<~'erb'
    <span title="<%= title %>"><%= content %> (<%= 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 :content, :title, :view_context
end