Use tag helpers rather than strings to assemble HTML
While slightly more verbose, Railsโ tag helpers have several advantages over composing HTML directly via strings. Helpers automatically sanitize HTML, preventing code injection attacks called Cross-Site Scripting (XSS).
Bad ๐
Hereโs an example of vulnerable code:
<div class="<%= color %>"></div>
Why is this dangerous? If color can be set by a user, a hacker could inject javascript:
color = "/><script>alert('hacked!')</script>"
#=> <div class="/><script>alert('hacked!')</script>"></div>
Good ๐
Use the content_tag helper, which properly sanitizes text content and attributes:
color = "/><script>alert('hacked!')</script>"
content_tag(div, class: color)
#=> <div class="/><script>alert('hacked!')</script>"></div>
Further reading ๐
https://cheatsheetseries.owasp.org/cheatsheets/Ruby_on_Rails_Cheat_Sheet.html