skip to content

Action View Templates

Action View turns controller state into HTML through ERB templates, layouts, partials, view helpers and component classes. Interviewers probe where view logic belongs and how output stays escaped.

part ofRuby on Railsread it →
on this pageshow

explore

questions

25

With the ViewComponent gem, what files make up a component, and how do you render one from a Rails view?

level: juniorimportance: must knowfreq 32%

answer

  1. a Ruby class plus a sidecar template
  2. subclass of ViewComponent::Base
  3. inputs arrive through initialize
  4. render(Component.new(...)) calls render_in
  5. generator lives under view_component:

basics

~10 s

A ViewComponent is a Ruby class inheriting from ViewComponent::Base, usually app/components/alert_component.rb, with a sidecar template beside it, alert_component.html.erb. A view renders it with render(AlertComponent.new(kind: :warning, message: "...")).

solid answer

~40 s

`bin/rails generate view_component:component Alert kind message` writes `app/components/alert_component.rb`, a class inheriting from `ApplicationComponent` if the app defines one, else `ViewComponent::Base`, with `def initialize(kind:, message:)`; a sidecar template `app/components/alert_component.html.erb`; and `test/components/alert_component_test.rb`. The template runs in the component instance, so it sees the component's instance variables and methods and none of the controller's instance variables. A view or controller calls `render(AlertComponent.new(kind: :warning, message: "Upload the police report"))`; Rails' `render` sees an object responding to `render_in` and hands it the view context. A block passed to `render` becomes `content`, `render?` returning false skips output, and `before_render` is the first point where `helpers` works. In ViewComponent 4 the generator is namespaced (`rails g component` is gone), and an instance renders once: a second render raises `ViewComponent::ReusedInstanceError`.

code

ruby · 15 lines
ruby
# app/components/alert_component.rb
class AlertComponent < ViewComponent::Base
  def initialize(kind:, message:)
    @kind = kind
    @message = message
  end

  def render?
    @message.present?
  end

  private

  def css_class = "alert alert--#{@kind}"
end

go deeper

for a junior

Know the class-plus-template pair, where the files live, the generator name, and render(AlertComponent.new(...)).

for a middle

Explain render_in, why the template sees only the component's state, the before_render and render? hooks, and how helpers are reached.

for a senior

Catch v3-to-v4 upgrade breakage, reused instances, and helpers called too early, and decide which widgets deserve components.

for a principal

Decide whether the app standardises on components for shared UI, and what the convention for inputs, naming and folders is.

## What a component is An insurance-claims portal shows the same **alert box** on many pages: a missing document, a rejected payment, a claim approved. As a partial it would read whatever locals and instance variables happen to be around. With the **ViewComponent** gem it becomes a Ruby object with explicit inputs and its own template. The generator shows the anatomy: ```bash bin/rails generate view_component:component Alert kind message ``` which writes: 1. `app/components/alert_component.rb` - the **class**, inheriting from `ApplicationComponent` when the app defines one, otherwise from `ViewComponent::Base`; 2. `app/components/alert_component.html.erb` - the **sidecar template**, found by name next to the class; 3. `test/components/alert_component_test.rb` - a unit test (or a spec, with RSpec configured). Options add more: `--preview` writes a preview class, `--sidecar` puts the template in an `alert_component/` folder, `--inline` puts the template in the class, and `--call` generates a `call` method instead of a template. ## The class and its template ```ruby class AlertComponent < ViewComponent::Base def initialize(kind:, message:) @kind = kind @message = message end def css_class = "alert alert--#{@kind}" end ``` ```erb <div class="<%= css_class %>" role="alert"><%= @message %></div> ``` The template is compiled into a method on the class, so inside it `self` is the component: - it sees the component's **instance variables** and **methods** (`@message`, `css_class`); - it does **not** see the controller's instance variables; `@claim` is `nil` there unless passed in; - Action View's own helpers (`link_to`, `tag`, `number_to_currency`) are available because `ViewComponent::Base` includes them; the app's helpers in `app/helpers` are reached through `helpers.claim_status_label(...)` or by including the module. ## Rendering it From any template, or from a controller action: ```erb <%= render(AlertComponent.new(kind: :warning, message: "Upload the police report")) %> ``` Rails' `render` checks whether its argument responds to **`render_in`**. ViewComponent implements that method, so Rails passes the current view context and inserts the returned HTML. Missing keyword arguments fail early with Ruby's `ArgumentError`, before any HTML is produced. ## Lifecycle hooks worth knowing | Hook | When it runs | Typical use | |---|---|---| | `initialize` | when you call `new` | store inputs; no view context yet | | `before_render` | after the view context is attached | read helpers, the request or `controller` | | `render?` | before the template | return `false` to render nothing | | `content` | when the template reads it | the block passed to `render` | Calling `helpers` inside `initialize` raises `ViewComponent::HelpersCalledBeforeRenderError`, because no view context exists yet. ## ViewComponent 4 details that trip upgrades - The generator moved to the `view_component:` namespace; the old `rails g component` is gone. - `ViewComponent::Base` no longer defines a catch-all initializer, so a component without its own `initialize` takes no arguments. - Since **4.14** an instance is **single-use**: rendering the same object twice raises `ViewComponent::ReusedInstanceError`, because state from the first render could leak into the second. Build a new instance per render; for lists, `with_collection` builds a fresh instance per item, passing it under a keyword named after the component (`alert:` for `AlertComponent`). - Preview and generator settings now live under `config.view_component.previews.*` and `config.view_component.generate.*`. ## Mistakes interviewers listen for | Belief | What ViewComponent actually does | |---|---| | the template can read `@claim` from the controller | it sees only the component's own state; pass the claim in | | components render with `render partial:` | they render as objects through `render_in` | | `rails g component` is the generator | in v4 it is `view_component:component` | | one instance can be reused for every row | since 4.14 a second render raises | | `helpers` works anywhere in the class | only once rendering has started, from `before_render` on | A junior answer that names the two files, the base class and the `render(...new(...))` call is enough to open the topic; the follow-ups usually probe the instance-variable boundary, because that is the property that makes a component different from a partial.

  • Why does @claim come out nil inside a component template when the controller set it?
    The template runs as a method on the component instance, so instance variables resolve on the component, not on the view or controller. Pass the claim in through `initialize` (for example `ClaimCardComponent.new(claim: @claim)`); that explicit input is the point of the component.
  • How do you call an app helper such as claim_status_label from inside a component?
    Use the `helpers` proxy, `helpers.claim_status_label(@claim)`, from `before_render` or the template, or include the helper module in the component. Calling `helpers` in `initialize` raises `HelpersCalledBeforeRenderError`, because the view context is attached only when rendering starts.

  • A component template can read the controller's instance variables
  • Components are rendered with render partial: "components/alert"
  • rails g component Alert is the ViewComponent 4 generator
  • You can build one AlertComponent instance and render it on every row
  • helpers is safe to call inside initialize

Assumes ViewComponent 4.15 on Rails 8.1: the generator is view_component:component since 4.0, and since 4.14 rendering one instance twice raises ViewComponent::ReusedInstanceError.

open as a page

In a Rails ERB template, how do <% %>, <%= %> and <%# %> differ, and what does <%= %> do to its value?

level: juniorimportance: must knowfreq 72%

basics

~20 s

In a Rails ERB template, <% %> runs Ruby without output, <%= %> runs it and appends the result to the page HTML-escaped unless it is html_safe, and <%# %> is a comment that never runs.

open as a page

In a Rails app, how does an action's view end up inside app/views/layouts/application.html.erb, and what does yield do there?

level: juniorimportance: must knowfreq 68%

basics

~10 s

In Rails, Action View renders the action's template first, then renders the controller's layout, by default layouts/<controller> or else layouts/application, and the layout's bare yield inserts the template's HTML at that point.

open as a page

In a Rails view, how do you render a partial such as _gig.html.erb and pass it data with locals:?

level: juniorimportance: must knowfreq 70%

basics

~20 s

In Rails, a partial is a template whose file name starts with an underscore, such as gigs/_gig.html.erb; render it with render partial: "gig", locals: { gig: @gig }, the shorthand render "gig", gig: @gig, or render @gig via to_partial_path.

open as a page

In Rails views, what does String#html_safe actually do, and how do raw and <%== %> relate to it and to SafeBuffer?

level: middleimportance: must knowfreq 62%

basics

~10 s

In Rails, String#html_safe wraps the string in an ActiveSupport::SafeBuffer marked trusted, without escaping or cleaning anything. raw(x) is x.to_s.html_safe, and <%== %> appends a value unescaped; all three only switch escaping off.

open as a page

In Rails views, how do content_for, yield :name, content_for? and provide pass a per-page title and extra head tags to the layout?

level: middleimportance: must knowfreq 52%

basics

~20 s

In Rails, content_for :name stores HTML in a named region, appending on each call; the layout reads it with yield :name or content_for(:name); content_for? tests whether it is filled; provide stores the same way but is built for streamed templates.

open as a page

In Rails, what do render @gigs and render partial: "gig", collection: do, and how do as:, spacer_template:, gig_counter and gig_iteration work?

level: middleimportance: must knowfreq 55%

basics

~20 s

Rails' render @gigs, or render partial: "gig", collection: @gigs, renders the partial once per element, exposing gig, gig_counter from 0 and gig_iteration; as: renames them, spacer_template: renders between items, and an empty collection returns nil.

open as a page

In a Rails view, what do truncate(listing.notes, length: 40) and pluralize(listing.tracks_count, "track") return, and what do they escape?

level: juniorimportance: should knowfreq 30%

basics

~20 s

truncate cuts text to at most :length characters including the "..." omission (default 30), HTML-escapes the result unless escape: false, and marks it safe. pluralize returns the count plus the singular or plural word, such as "1 track" or "12 tracks".

open as a page

In ViewComponent, how do renders_one and renders_many give a card component header and action regions, and how does a caller fill them?

level: middleimportance: should knowfreq 28%

basics

~20 s

renders_one :header and renders_many :actions declare named regions. The caller fills them inside the render block with card.with_header { ... } and card.with_action(...), and the template prints header, iterates actions, checks header? and prints content for the body.

open as a page

In a Rails view, how does sanitize decide which tags and attributes of a member bio survive, and how do strip_tags and strip_links differ?

level: middleimportance: should knowfreq 45%

basics

~10 s

Rails' sanitize keeps only tags and attributes on an allowlist, removes other elements but keeps their text, drops unsafe URL protocols and returns an html_safe string. strip_tags removes every tag; strip_links removes only links.

open as a page

In Rails, how does Action View turn ProfilesController#show into a template file, and what does each part of show.html.erb mean?

level: middleimportance: should knowfreq 42%

basics

~20 s

Rails' Action View searches each view path, app/views first, under the controller's prefixes, such as profiles then application, for a file named after the action, filtered by locale, format, variant and handler: show.html.erb is action show, format html, handler erb.

open as a page

On a Rails listing page, what do number_to_currency(listing.price) and time_ago_in_words(listing.created_at) output, and which defaults trip people up?

level: middleimportance: should knowfreq 38%

basics

~20 s

number_to_currency formats a number with the current locale's currency settings (in en: "$1,234.50") but never converts it. time_ago_in_words returns an approximate distance from now such as "about 2 hours" or "3 days", with no "ago" and no past or future direction.

open as a page

In Action View, what does dom_id return for a saved record, a new record and a prefix argument, and why use it?

level: middleimportance: should knowfreq 45%

basics

~10 s

dom_id(listing) returns "listing_42"; for an unsaved record or the class it returns "new_listing"; dom_id(listing, :edit) returns "edit_listing_42". One naming rule lets views, Turbo Stream targets, forms and tests address the same element.

open as a page

In Action View, how does the tag builder (tag.div, tag.span) differ from content_tag, and what does it escape and expand?

level: middleimportance: should knowfreq 42%

basics

~20 s

tag.div(content, **attributes) is the current tag-builder API and content_tag(:div, content, attributes) the older positional form; both return an html_safe string, escape content and attribute values unless already safe, and expand data:, aria:, class arrays and boolean attributes.

open as a page

In a Rails controller, how do layout "staff", layout :method, layout false and only:/except: pick a layout, and how does render layout: override them?

level: middleimportance: should knowfreq 42%

basics

~20 s

In a Rails controller, layout "staff" names a template in app/views/layouts, layout :method decides per request, layout false turns layouts off, and only:/except: limit which actions get it; render layout: overrides all of that for one render.

open as a page

In a Rails app, when does a ViewComponent or Phlex component beat a partial, and what does adopting components cost the team?

level: seniorimportance: should knowfreq 34%

basics

~20 s

A component beats a partial for reused UI with logic or variants: inputs are explicit, logic lives in testable methods, and render_inline tests run without a browser. The cost is another dependency and convention, helpers reached explicitly, and single-use instances.

open as a page

How do you unit-test a ViewComponent with render_inline, and what do ViewComponent previews add beyond those tests?

level: seniorimportance: should knowfreq 24%

basics

~20 s

render_inline(AlertComponent.new(...)) renders the component through a test controller's view context, returns a Nokogiri fragment and sets page for Capybara assertions, with no browser or routing. Previews render the same components at /rails/view_components in development for visual review.

open as a page

A Rails helper calls gsub on a sanitized member bio and the page now shows escaped tags; how do SafeBuffer's string methods, + and safe_concat explain it?

level: seniorimportance: should knowfreq 28%

basics

~20 s

ActiveSupport::SafeBuffer's transforming methods such as gsub, sub and upcase return a plain String, so <%= %> escapes the sanitized markup again. Its +, << and % escape unsafe arguments, and safe_concat raises SafeConcatError on an unsafe buffer.

open as a page

For a dating app's phone screens, how does Rails choose profiles/show.html+phone.erb over show.html.erb, and what happens when no phone file exists?

level: seniorimportance: should knowfreq 22%

basics

~20 s

When the controller sets request.variant to :phone, Rails' template lookup requests that variant and ranks show.html+phone.erb above show.html.erb; if no +phone file exists, the variant-less template matches and renders. With no variant set, +phone files are never chosen.

open as a page

In a Rails app, why can a method from app/helpers/listings_helper.rb be called in every view, and what does include_all_helpers = false change?

level: seniorimportance: should knowfreq 32%

basics

~10 s

By default ApplicationController, as a direct ActionController::Base subclass, calls helper :all, so every app/helpers module reaches every view. With config.action_controller.include_all_helpers = false, each controller gets only its matching helper plus inherited ones.

open as a page

How do you build a nested Rails layout, such as a museum staff layout that reuses application.html.erb, with content_for and render template:?

level: seniorimportance: should knowfreq 24%

basics

~20 s

In Rails, an inner layout such as layouts/staff.html.erb fills regions with content_for, typically :content and :head, then calls render template: "layouts/application"; the outer layout prints content_for?(:content) ? yield(:content) : yield, so it serves both plain and nested pages.

open as a page

A Rails concert-listings page renders 500 gig cards with render inside an each loop and is slow; what does a partial cost per call, and what helps?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Each Rails partial render pays for option handling, a template lookup and instrumentation; a collection render pays that once for the whole list. Queries and nested partials inside each card usually cost more and should be fixed first.

open as a page

What does a Rails strict locals magic comment such as <%# locals: (gig:, compact: false) -%> enforce in a partial, and why add one?

level: seniorimportance: should knowfreq 28%

basics

~20 s

A Rails strict locals comment gives a partial a keyword-argument signature: required locals must be passed, unknown ones are rejected, defaults fill the rest, and the partial compiles once instead of once per combination of locals passed.

open as a page

In Phlex 2 with phlex-rails, how does a Phlex::HTML component produce markup, and how does it call Rails helpers such as link_to?

level: middleimportance: nice to knowfreq 14%

basics

~20 s

A Phlex component is a Ruby class inheriting from Phlex::HTML whose view_template method calls element methods such as div and p with blocks; output is escaped by default. Rails helpers are included as phlex-rails adapters, e.g. include Phlex::Rails::Helpers::LinkTo.

open as a page