Class: ActionView::Component::Base

Inherits:
Base
  • Object
show all
Includes:
ActionController::RequestForgeryProtection, ActiveModel::Validations, ActiveSupport::Configurable
Defined in:
lib/action_view/component/base.rb

Defined Under Namespace

Classes: DummyTemplate

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeBase

Returns a new instance of Base.



74
# File 'lib/action_view/component/base.rb', line 74

def initialize(*); end

Class Method Details

.compileObject

Compile template to #call instance method, assuming it hasn’t been compiled already. We could in theory do this on app boot, at least in production environments. Right now this just compiles the template the first time the component is rendered.



94
95
96
97
98
99
100
# File 'lib/action_view/component/base.rb', line 94

def compile
  return if @compiled && ActionView::Base.cache_template_loading

  class_eval("def call; @output_buffer = ActionView::OutputBuffer.new; #{compiled_template}; end")

  @compiled = true
end

.inherited(child) ⇒ Object



85
86
87
88
89
# File 'lib/action_view/component/base.rb', line 85

def inherited(child)
  child.include Rails.application.routes.url_helpers unless child < Rails.application.routes.url_helpers

  super
end

Instance Method Details

#render(options = {}, args = {}, &block) ⇒ Object



76
77
78
79
80
81
82
# File 'lib/action_view/component/base.rb', line 76

def render(options = {}, args = {}, &block)
  if options.is_a?(String) || (options.is_a?(Hash) && options.has_key?(:partial))
    view_context.render(options, args, &block)
  else
    super
  end
end

#render_in(view_context, *args, &block) ⇒ Object

Entrypoint for rendering components. Called by ActionView::Base#render.

view_context: ActionView context from calling view args(hash): params to be passed to component being rendered block: optional block to be captured within the view context

returns HTML that has been escaped by the respective template handler

Example subclass:

app/components/my_component.rb: class MyComponent < ActionView::Component::Base

def initialize(title:)
  @title = title
end

end

app/components/my_component.html.erb <span title=“<%= @title %>”>Hello, <%= content %>!</span>

In use: <%= render MyComponent, title: “greeting” do %>world<% end %> returns: <span title=“greeting”>Hello, world!</span>



61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/action_view/component/base.rb', line 61

def render_in(view_context, *args, &block)
  self.class.compile
  self.controller = view_context.controller
  @view_context = view_context
  @view_renderer ||= view_context.view_renderer
  @lookup_context ||= view_context.lookup_context
  @view_flow ||= view_context.view_flow

  @content = view_context.capture(&block) if block_given?
  validate!
  call
end