title: Why in Rails 3, <%= note.html_safe %> and <%= h note.html_safe %> give the same result?
body: <p>It feels like <code>html_safe</code> adds an abstraction to the String class that requires understanding of what is going on, for example,</p>
  
  <pre><code>&lt;%= '1 &lt;b&gt;2&lt;/b&gt;' %&gt;      # gives 1 &amp;lt;b&amp;gt;2&amp;lt;/b&amp;gt; in the HTML source code
  
  &lt;%= h '1 &lt;b&gt;2&lt;/b&gt;' %&gt;    # exactly the same as above
  
  &lt;%= '1 &lt;b&gt;2&lt;/b&gt;'.html_safe %&gt;      #  1 &lt;b&gt;2&lt;/b&gt;  in HTML source code
  
  &lt;%= h '1 &lt;b&gt;2&lt;/b&gt;'.html_safe %&gt;    #  exactly the same as above
  
  &lt;%= h (h '1 &lt;b&gt;2&lt;/b&gt;') %&gt;  #  1 &amp;lt;b&amp;gt;2&amp;lt;/b&amp;gt;   wont' escape twice
  </code></pre>
  
  <p>For line 4, if we are saying, ok, we trust the string -- it is safe, but why can't we escape it?  It seems that to escape it by <code>h</code>, the string has to be unsafe.</p>
  
  <p>So on line 1, if the string is not escaped by <code>h</code>, it will be automatically escaped.  On line 5, <code>h</code> cannot escape the string twice -- in other words, after <code>&lt;</code> is changed to <code>&amp;lt;</code>, it can't escape it one more time to <code>&amp;amp;lt;</code>.</p>
  
  <p>So what's happening?  At first, I thought <code>html_safe</code> is just tagging a flag to the string, saying it is safe.  So then, why does <code>h</code> not escape it?  It seems that <code>h</code> and <code>html_escape</code> actually co-operate on using the flag:</p>
  
  <p>1) If a string is html_safe, then <code>h</code> will not escape it</p>
  
  <p>2) If a string is not html_safe, then when the string is added to the output buffer, it will be automatically escaped by <code>h</code>.</p>
  
  <p>3) If <code>h</code> already escaped a string, it is marked <code>html_safe</code>, and therefore, escaping it one more time by <code>h</code> won't take any effect. (as on Line 5, and that behavior is the same even in Rails 2.3.10, but on Rails 2.3.5 <code>h</code> can actually escape it twice... so in Rails 2.3.5, <code>h</code> is a simple escape method, but some where along the line to 2.3.10, <code>h</code> became not as simple.  But 2.3.10 won't auto escape a string, but for some reason, the method <code>html_safe</code> already exists for 2.3.10 (for what purpose?))</p>
  
  <p>Is that how it works exactly?  I think nowadays, sometimes we don't get what we want in the output and we immediately add <code>html_safe</code> to our variable, which can be quite dangerous, because it can introduce XSS attack that way, so understanding how it exactly works can be quite important.  The above is only a guess of how it exactly work.  Could it be actually a different mechanism and is there any doc that supports it?</p>