A simple code snippet for displaying your flash[:warning] = “Warning Message” messages in rails.
Add the following to your application_helper.rb.
def flash_helper
f_names = [:notice, :warning, :message]
fl = ''
for name in f_names
if flash[name]
fl = fl + "<div class=\"notice\">#{flash[name]}</div>"
end
flash[name] = nil;
end
return fl
end
To show all messages place this code in your view (rhtml).
<%= flash_helper %>
Also here’s some CSS to style the messages.
div.notice {
margin-left: auto;
margin-right: auto;
text-align: center;
width: 40%;
border: 5px solid #ccc;
margin-top: 50px;
padding: 20px;
font-weight: bold;
}
Mark
Thank You
Link | April 18th, 2007 at 2:27 am
Dallas
You really should not put xhtml code into your helpers. Keep your content, layout, functional code, and styles separate.
Link | May 31st, 2007 at 12:05 pm
S. Potter
I use a more terse version of what your code does:
def render_flash_messages result = '' for type in [:notice, :warning, :message] message = flash[type] # commented out content_tag, while cleaner is very inefficient #content_tag('div', message, :class => type) if message # using string inline method... result #{message}" end result endA few things should be noted:
flash_helper and render_flash_messages are roughly equivalent performance wiseflash_helper has a defect in it. Line 8 should read:
fl = fl + â€#{flash[name]}â€Link | July 2nd, 2007 at 9:36 pm
S. Potter
Formatting of previous comment (or lackthereof) may cause misunderstanding. Code should read:
def render_flash_messages result = '' for type in [:notice, :warning, :message] message = flash[type] result #{message}†end result endI should also note that content_tag is quite slow, which is why I used the inline string to generate HTML. If a partial was used instead (for the MVC purist, which I am usually) that would have incurred an even higher performance hit, which in most of my applications isn’t worth the extra purity of the code.
Link | July 2nd, 2007 at 9:40 pm
Adam Salter
here’s another version of the above, even more terse…
def flash_helper
[:notice, :warning, :message].map { |f| content_tag(:div, flash[f], :class => type) if flash[f] }
end
Link | December 10th, 2007 at 5:24 pm
Adam Salter
woops, I mean
def flash_helper
[:notice, :warning, :message].map { |f| content_tag(:div, flash[f], :class => f) if flash[f] }
end
Link | December 10th, 2007 at 5:28 pm
Jarrod
@Dallas
I disagree… I think having a little markup in your helpers is perfectly acceptable. They are “help” for your presentation after all. I think the main mistake people make is using helpers for things that should go into a partial.
Link | March 13th, 2008 at 9:09 am
spannarissuro
OK, let me repeat that… Do you have a sense of wonder about my comfortable doubt A JOKE! ) What is three feet long? A yard.
Link | October 28th, 2008 at 5:05 pm