In Rails 7.1, developers can define or restrict local variables a template can accept. To implement this, you must add a local magic comment inside the template.

# app/views/shared/_payment_gateways.html.erb

<%# locals: (paypal:, braintree:) -%>

ref. Rails 7.1 gives templates more control over the locals they receive | Shakacode

Rails PR

実装されたRailsのPRはこちら。

Allow templates to define which locals they accept by joelhawksley · Pull Request #45602 · rails/rails

Before:

<%# issues/_card.html.erb %>
<% title = local_assigns[:title] || "Default title" %>
<% comment_count = local_assigns[:comment_count] || 0 %>
<h2><%= title %></h2>
<span class="comment-count"><%= comment_count %></span>

After:

<%# issues/_card.html.erb %>
<%# locals: (title: "Default title", comment_count: 0) %>
<h2><%= title %></h2>
<span class="comment-count"><%= comment_count %></span>

結論

下記の理由からRails 7.1のこの機能は便利。

  • テンプレートのローカル変数のデフォルト値を設定できる
  • テンプレートに渡すローカル変数のバリデーションとして機能する