skip to content

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%

answer

  1. a keyword-argument signature for a partial
  2. missing local and unknown local errors
  3. locals: () accepts none
  4. one compiled method, not one per key set
  5. defaults are not in local_assigns

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.

solid answer

~50 s

Since Rails 7.1, a `<%# locals: (...) -%>` comment anywhere in a template declares its locals with Ruby keyword-argument syntax. `gig:` is required, `compact: false` has a default, `**options` accepts extras and `locals: ()` accepts none. Rendering without `gig` or with an unexpected key fails with an `ActionView::Template::Error` whose message reads like `missing local: :gig` or `unknown local: :venue` for the partial's path; in 8.1 the underlying error is `ActionView::StrictLocalsError`, an `ArgumentError` subclass. Only keyword arguments are allowed. Defaults are local variables but are not added to `local_assigns`. Besides documenting the interface and catching typos, it lets Action View compile one method for the partial instead of one per distinct set of locals. In collection renders, `gig_counter` and `gig_iteration` reach the partial only if the signature declares them, or inside the `**` Hash if it has one.

code

erb · 12 lines
erb
<%# app/views/gigs/_gig.html.erb %>
<%# locals: (gig:, compact: false, gig_counter: nil) -%>
<article class="gig<%= " gig--compact" if compact %>">
  <% if gig_counter %><span><%= gig_counter + 1 %>.</span><% end %>
  <h2><%= gig.band_name %></h2>
</article>

<%# callers %>
<%= render "gigs/gig", gig: @gig %>                       <%# ok, compact defaults to false %>
<%= render "gigs/gig", gig: @gig, compact: true %>        <%# ok %>
<%= render "gigs/gig", gig: @gig, show_venue: false %>    <%# unknown local: :show_venue %>
<%= render partial: "gigs/gig", collection: @gigs %>      <%# gig_counter passed: declared %>

go deeper

for a junior

Recognise the locals: comment at the top of a partial as the list of locals it expects.

for a middle

Read a signature: required keys, defaults, ** and (), and know the missing local and unknown local errors.

for a senior

Explain the compile-once benefit, the local_assigns and collection-counter gotchas, and roll signatures out on shared partials first.

for a principal

Decide whether explicit partial interfaces are enough or the team should move shared UI to component classes.

## The problem strict locals solve A classic Rails partial accepts any locals. Action View compiles each template into a Ruby method, and because Ruby cannot create local variables dynamically, a partial without a declared signature is compiled **once per distinct set of local names** it is rendered with. `render "gig", gig: g` and `render "gig", gig: g, compact: true` produce two compiled methods. On a large app with partials called many ways, that costs memory and compile time. The partial's inputs are also invisible: you learn them by reading its body, and a typo such as `show_venu: false` is silently ignored. ## The magic comment Rails 7.1 added **strict locals**: a comment that declares the partial's signature with Ruby keyword-argument syntax. ```erb <%# app/views/gigs/_gig.html.erb %> <%# locals: (gig:, compact: false, **html_options) -%> ``` | Signature part | Meaning | |---|---| | `gig:` | required local | | `compact: false` | optional, with a default | | `**html_options` | any other keys, collected into a Hash | | `locals: ()` | the partial accepts no locals at all | The comment can sit on any line of the template and works in any template engine that has `#` comments. Only keyword arguments are allowed; a positional or block parameter in the signature raises at render time, when the template is compiled. ## What happens on a mismatch - Missing a required local: rendering fails with `ActionView::Template::Error`, message `missing local: :gig for app/views/gigs/_gig.html.erb`. - Passing an unexpected key without `**`: `unknown local: :venue for ...`. - Passing anything to a `locals: ()` partial: `no locals accepted for ...`. In Rails 8.1 these come from `ActionView::StrictLocalsError`, a subclass of `ArgumentError`. Earlier versions rewrote any `ArgumentError` raised during rendering, which could disguise a real bug in a helper call as a locals problem; 8.1 re-raises unrelated argument errors with their own backtrace. ## Details that trip people up 1. **`local_assigns` holds only what was passed.** A default from the signature is a real local variable but is not added to `local_assigns`, so `local_assigns[:compact]` is `nil` when the caller relied on the default. Read the variable instead. 2. **Collection counters must be declared.** In `render partial: "gig", collection: @gigs`, Rails offers `gig_counter` and `gig_iteration` as implicit locals; with a strict signature they are dropped unless the signature lists them, for example `gig_counter: nil`; a `**options` catch-all receives them as keys of that Hash rather than as variables. 3. **Reserved words as names.** A local called `class` cannot be read as a variable; the guides show `binding.local_variable_get(:class)` for that case. 4. **Instance variables still work.** Strict locals restrict locals, not `@venue`; enforce that through review. ## Reading a signature at a glance A reviewer can answer three questions from the first line of a strict partial: which locals must every caller pass (the keys without defaults), which are optional and what they default to, and whether extra keys are tolerated (a `**` catch-all) or rejected. That is the same contract a Ruby method signature gives, which is the point: partials become callable units with a declared interface rather than templates that read whatever happens to be in scope. ## Why a team adopts them - **A visible interface.** The first line of the partial says what it needs, like a method signature. - **Early, precise errors.** A renamed local fails loudly at the call site's render, in tests, instead of rendering a card without its venue. - **One compiled method per partial.** Memory and warm-up time stop growing with the number of distinct call shapes. - **A step towards components.** Partials with explicit inputs are easier to move into ViewComponent or Phlex later if the team chooses to. The cost is small: one comment per partial and the discipline of updating it. Large apps often adopt them on shared partials first.

  • Why does a partial with strict locals use less memory than one without?
    Action View compiles each template into a method. Without a signature it must compile a separate method for every distinct set of local names callers pass, because Ruby cannot add local variables at run time. A declared signature becomes the method's keyword arguments, so one compiled method serves every caller.
  • How would you roll strict locals out across an existing app?
    Start with the most shared partials, add a signature that matches how they are called today, and run the test suite and system tests, which surface every `missing local` or `unknown local` mismatch. Fix call sites or widen the signature with defaults, then repeat for the next partials.

  • Strict locals are declared with a strict_locals! call in the controller.
  • A default value in the signature also appears in local_assigns.
  • Positional parameters work in the locals: comment like keywords do.
  • locals: () means the partial accepts any locals.
  • Strict locals forbid reading instance variables in the partial.

Assumes Rails 8.1; strict locals arrived in Rails 7.1, and 8.1 raises ActionView::StrictLocalsError for signature mismatches instead of re-raising any ArgumentError.