html_safe and helpers in rails 3. Mystery solved.

html_safe and helpers in rails 3 – Rails 2 vs 3

In Rails 3 (contrary to Rails 2) Strings are automatically escaped using ERB::Util.h(string) and the reason is simple. In 95% of the cases you won’t have to print html code inside ruby strings like this:
< %="<h1>Hello World"%>
In Rails 2 for this 95% of the cases you had to call the “h” helper to escape the output which was really annoying and insecure (if you forgot one).

Although this was the case for views, constructing a helper that prints html content became tricky in Rails 3. If you want your html content to stay unescaped it has to be an ActiveSupport::SafeBuffer instance instead of a String instance. To achieve this there are two solutions: Continue reading

How to write case statement into views – Rails quick tips

Case statement in a view – Fail!

Well I can’t recall when (and why) but one time I was writing a view in a Rails project and needed to write a case statement (of course I could have done it with usual if / else /elsif statement, but the case statement seemed more natural). My first try (and I remember I was pretty confident that this was the way to go) had gone like this: Continue reading