Performance: View helpers
View helpers affect how quickly HTML is generated and rendered, impacting page load speed and responsiveness.
def user_list(users) content_tag :div, class: 'users' do safe_join(users.map { |user| content_tag(:div, content_tag(:span, user.name), class: 'user') }) end end
def user_list(users) users.map do |user| "<div class='user'>" + "<span>#{user.name}</span>" + "</div>" end.join end
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual string concatenation in helpers | No direct DOM ops but generates verbose HTML | Triggers multiple reflows if HTML is large | Higher paint cost due to larger HTML | [X] Bad |
| Using Rails content_tag and safe_join helpers | Generates clean HTML with minimal nodes | Single reflow after full HTML is parsed | Lower paint cost due to optimized markup | [OK] Good |
app/helpers/application_helper.rb:
def greeting(name)
"Hello, #{name}!"
end
What will this ERB code output?
<%= greeting('Alice') %>def format_price(price)
"$#{price.round(2)}"
end
But in your view, calling <%= format_price(5) %> shows an error: NoMethodError: undefined method 'round' for 5:Integer. What is the problem?Pass the test and this pattern moves unknown