Performance: ERB template syntax
ERB template syntax affects how HTML and Ruby code are combined and rendered on the server, impacting server response time and initial page load speed.
<% @processed_items = @items.map { |item| expensive_method_call(item) } %>
<% @processed_items.each do |processed| %>
<%= processed %>
<% end %><% @items.each do |item| %> <%= expensive_method_call(item) %> <% end %>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Expensive Ruby calls inside ERB | N/A (server-side) | N/A | N/A | [X] Bad |
| Precomputed data passed to ERB | N/A (server-side) | N/A | N/A | [OK] Good |
<%= %> tag evaluates Ruby code and inserts the result into the HTML.<% %> runs Ruby code without output, <%# %> is a comment, and <%== %> is not standard ERB syntax.<% %> tag runs Ruby code but does not insert output into HTML.<%= %> outputs result, <%# %> is a comment, and <%== %> is invalid syntax.<ul>
<% items.each do |item| %>
<li><%= item.upcase %></li>
<% end %>
</ul>items = ['apple', 'banana']?item.upcase.<li> tags with uppercase text, so the list shows APPLE and BANANA.<ul>
<% items.each do |item| %>
<li><% item.upcase %></li>
<% end %>
</ul><% item.upcase %> which runs Ruby but does not output anything.<%= item.upcase %> instead.user.admin? is true. Which snippet correctly does this?<% if user.admin? %> starts an if block where literal text like "Welcome, admin!" is rendered only if true, ended by <% end %>.: '').Pass the test and this pattern moves unknown