Skip to content

Instantly share code, notes, and snippets.

@jpgeek
Created October 26, 2012 11:37
Show Gist options
  • Save jpgeek/3958309 to your computer and use it in GitHub Desktop.
Save jpgeek/3958309 to your computer and use it in GitHub Desktop.
Rails 3 HTML escaping
String output from html helpers like link_to are html_safe.
In the console:
lnk = helper.link_to('home', '/')
=> "<a href=\"/\">home</a>"
lnk.html_safe?
=> true
However, if you have html-ish stuff in the text arguments to the helper,
it must be html_safe blessed:
helper.link_to('home', '<tag>')
=> "<a href=\"&lt;tag&gt;\">home</a>"
BUT
helper.link_to('home', '<tag>'.html_safe)
=> "<a href=\"<tag>\">home</a>"
# Moving them around doesn't hurt:
links = []
links << lnk
links[0].html_safe? # true
Strings are by default not html safe:
"foo".html_safe?  # false
Concatenation with anything unsafe causes it all to be unsafe:
("foo" + lnk).html_safe? # false
("foo".html_safe + lnk).html_safe? # true
Careful with Array.join:
links << "foo".html_safe
links.join.html_safe? # false WTF?
(links[0] + links[1]).html_safe? # true
links[0].class # ActiveSupport::SafeBuffer
links.join.class # String
The Array.join creates a new string and shoves it all in, thus losing
the ActiveSupport::SafeBuffer and all its html_safe goodness.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment