views:

53

answers:

2

I have a flash_helper that I inconveniently downloaded from some web tutorial, which is now coming back to whack me on the head. On the good side, I'm sure the many talented coders here will find this easy. :)

# application_helper
def flash_helper
[:notice, :warning, :message].map { |f| content_tag(:div, flash[f], :class => f) if flash[f] }
end

This code, combined with <%= flash_helper %> in my views, is leading to the following html code generated:

[&quot;&lt;div class=\&quot;notice\&quot;&gt;Your account has been reactivated.&lt;/div&gt;&quot;, nil, nil]

...which renders as this rather unattractive string in the view itself:

["<div class=\"notice\">Your account has been reactivated.</div>", nil, nil]

How do I rewrite the code to sort this out?


[nil, nil, nil]

The above string is being sent to all of my views by the flash_helper code above when there is no flash. How can that code be rewritten to output nothing when there is no flash?

A: 

By default Rails 3 escapes HTML unless told otherwise. All you need to do is call .html_safe on the string being generated. Here is an overview:

HTML SAFE

sosborn
@sosborn: thanks for your answer. With <%= flash_helper.html_safe %>, I'm now getting the following error: undefined method `html_safe' for [nil, nil, nil]:Array.
sscirrus
You have to call it in the method, not on the output.
Jimmy
+1  A: 

You need launch html_safe on all your String, on an array.

# application_helper
def flash_helper
  [:notice, :warning, :message].map { |f| 
    content_tag(:div, flash[f].html_safe, :class => f) if flash[f] 
  }.compact
end
shingara
Hi Shingara, thanks very much. This certainly saves me from having to add html_safe to every view! I'm still getting [nil,nil,nil] displaying on views that have no flash.
sscirrus
so compact it after. I update my answer
shingara
This is because you need to check for nil before you call the method. Basically, if you have a flash then call flash_helper, otherwise don't call it. This should get you the behaviour you want.
sosborn
Hi Sosborn, calling for nil doesn't work because this helper outputs "[nil, nil, nil]". How can I rewrite the above code so it exports nothing at all when there is no flash?
sscirrus
Shingara - the .compact has reduced the [nil,nil,nil] to []. How can I lose the final pair of brackets please?
sscirrus
x = []; x.empty? ? nil : x
shingara
Thank you very much Shingara. It works perfectly now.
sscirrus