Skip to content

Instantly share code, notes, and snippets.

@simonbaird
Created September 20, 2011 04:59
Show Gist options
  • Save simonbaird/1228368 to your computer and use it in GitHub Desktop.
Save simonbaird/1228368 to your computer and use it in GitHub Desktop.
html_safe gotcha
#
# This is pretty confusing until you know what's going on...
#
# See http://techspry.com/ruby_and_rails/html_safe-and-helpers-in-rails-3-mystery-solved/
# for an explanation...
#
ruby-1.8.7-p334 :025 > foo_safe = "<p>foo</p>".html_safe
=> "<p>foo</p>"
ruby-1.8.7-p334 :026 > (foo_safe + "<p>bar</p>").html_safe # not what you thought! unintuitive!
=> "<p>foo</p>&lt;p&gt;bar&lt;/p&gt;"
ruby-1.8.7-p334 :027 > "#{foo_safe}<p>bar</p>".html_safe # I think it works because of the implicit to_s
=> "<p>foo</p><p>bar</p>"
ruby-1.8.7-p334 :028 > foo_safe.safe_concat("<p>bar</p>") # correct, but looks pretty clunky, right?
=> "<p>foo</p><p>bar</p>"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment