Skip to content

Instantly share code, notes, and snippets.

@jpgeek
Created October 26, 2012 11:37

Revisions

  1. jpgeek created this gist Oct 26, 2012.
    41 changes: 41 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    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.