Created
November 10, 2011 01:08
-
-
Save mahemoff/1353765 to your computer and use it in GitHub Desktop.
Rails 3+ Display Flashes, with option to choose if HTML is escaped or not
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# extends http://snippets.dzone.com/posts/show/2348 | |
# to include an option for escaping control | |
# flash[:success] = 'it worked!' will escape (safe) as per Rails 3 security measure, which | |
# defaults content_tag escaping to true | |
# flash[:explicit_success] = 'it <b>worked</b>!' will | |
module ApplicationHelper | |
FLASH_TYPES = [:error, :warning, :success, :notice] | |
def display_flashes(message = 'There were some problems with your submission:') | |
explicit = false | |
for flash_type in FLASH_TYPES | |
if explicit_flash = flash["explicit_#{flash_type}".to_sym] | |
explicit = true | |
flash.now[flash_type] = explicit_flash | |
break | |
end | |
end | |
if flash[:success] | |
flash_to_display, level = flash[:success], 'success' | |
elsif flash[:notice] | |
flash_to_display, level = flash[:notice], 'notice' | |
elsif flash[:warning] | |
flash_to_display, level = flash[:warning], 'warning' | |
elsif flash[:error] | |
level = 'error' | |
if flash[:error].instance_of? ActiveRecord::Errors | |
flash_to_display = message | |
flash_to_display << activerecord_error_list(flash[:error]) | |
else | |
flash_to_display = flash[:error] | |
end | |
else | |
return | |
end | |
content_tag 'div', flash_to_display, { :class => "flash #{level}" }, !explicit | |
end | |
def activerecord_error_list(errors) | |
error_list = '<ul class="error_list">' | |
error_list << errors.collect do |e, m| | |
"<li>#{e.humanize unless e == "base"} #{m}</li>" | |
end.to_s << '</ul>' | |
error_list | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment