Rails uses ActiveSupport::SafeBuffer to prevent cross-site scripting attacks. But when a string will or won’t be escaped can be confusing. Part of this confusion stems from when the unsafe string is actually escaped.
After doing some heavy #html_safe work we thought it would be helpful to create a cheat sheet containing the most common use cases.
Cheat sheet entries reference the following variables:
safe   = "<a href='#foo'>click here</a>".html_safe
unsafe = "<script>someMeanJavaScript()</script>"
| Operation | Result is html_safe? | Notes | 
|---|---|---|
| safe << unsafe | true | unsafeis escaped immediately | 
| safe += unsafe | true | unsafeis escaped immediately | 
| unsafe << safe | false | escaped when view is rendered | 
| unsafe += safe | false | escaped when view is rendered | 
| "Amaaaaaazing content: #{safe}" | false | escaped when view is rendered | 
| safe.to_s | true | — | 
| safe.to_str | false | More on #to_str | 
| safe.safe_concat(unsafe) | — | raises a SafeConcatError | 
| safe.safe_concat("foo".html_safe) | true | — |