Skip to content

Instantly share code, notes, and snippets.

@peshi
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peshi/edf8943efda74ea6bcbb to your computer and use it in GitHub Desktop.
Save peshi/edf8943efda74ea6bcbb to your computer and use it in GitHub Desktop.
Rails Bootstrap 3 Flash message helper
module FlashHelper
# Helper for Bootstrap styled flash messages.
def bootstrap_class_for(flash_type)
case flash_type
when 'success'
'alert alert-success alert-dismissable fade in' # Green
when 'error'
'alert alert-danger alert-dismissable fade in' # Red
when 'alert'
'alert alert-warning alert-dismissable fade in' # Yellow
when 'notice'
'alert alert-info alert-dismissable fade in' # Blue
else
flash_type.to_s
end
end
def flash_messages(options = {})
@layout_flash = options.fetch(:layout_flash) { true }
@flash_close = options.fetch(:closable) { true }
capture do
flash.each do |name, msg|
concat(content_tag(:div, class: bootstrap_class_for(name), role: 'alert') do
if @flash_close
concat(button_tag(type: :button, name: nil, class: :close, data: { dismiss: 'alert'}) do
concat content_tag(:span, '×'.html_safe, :'aria-hidden' => 'true')
concat content_tag(:span, 'Close', class: 'sr-only')
end)
concat msg
else
concat msg
end
end)
end
end
end
def show_layout_flash?
@layout_flash.nil? ? true: @layout_flash
end
end
@peshi
Copy link
Author

peshi commented Jun 29, 2014

Usage:
application.html.erb

<%= flash_messages closable: true if show_layout_flash? %>

If you would like to show errors elsewhere in your HTML

Example for devise:
views/devise/sessions/new.html.erb

<%= flash_messages layout_flash: false, closable: false %>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment