Skip to content

Instantly share code, notes, and snippets.

@suryart
Last active October 26, 2023 00:16
Show Gist options
  • Save suryart/7418454 to your computer and use it in GitHub Desktop.
Save suryart/7418454 to your computer and use it in GitHub Desktop.
Rails 4 flash messages using Twitter Bootstrap(bootstrap-sass: https://github.com/thomas-mcdonald/bootstrap-sass). An improved version of https://gist.github.com/roberto/3344628
// layout file
<body>
<div class="container">
<%= flash_messages %>
<%= yield %>
</div><!-- /container -->
</body>
module ApplicationHelper
def bootstrap_class_for flash_type
{ success: "alert-success", error: "alert-danger", alert: "alert-warning", notice: "alert-info" }[flash_type] || flash_type.to_s
end
def flash_messages(opts = {})
flash.each do |msg_type, message|
concat(content_tag(:div, message, class: "alert #{bootstrap_class_for(msg_type)} fade in") do
concat content_tag(:button, 'x', class: "close", data: { dismiss: 'alert' })
concat message
end)
end
nil
end
end
@davegson
Copy link

davegson commented May 10, 2018

A very basic and simple solution for Bootstrap 4:

application_helper.rb

module ApplicationHelper
  def bootstrap_class_for(flash_type)
    {
      success: 'alert-success',
      error: 'alert-danger',
      alert: 'alert-warning',
      notice: 'alert-primary'
    }[flash_type.to_sym] || flash_type.to_s
  end
end

application.html.erb

<!DOCTYPE html>
<html>
  <head>
    <!-- . -->
    <!-- . -->
  </head>
  <body>
    <div class='container'>
      <% flash.each do |type, content| %>
        <%= render 'partials/flash', type: type, content: content %>
      <% end %>

      <%= yield %>
    </div>
  </body>
</html>

_app/views/partials/flash.html.erb

<div class="alert <%= bootstrap_class_for(type) %> alert-dismissible fade show" role="alert">
  <button type="button" class="close" data-dismiss="alert" data-aria-label="Close">
    <span aria-hidden="true">&times;</span>
  </button>
  <div class="text">
    <%= content %>
  </div>
</div>

@superbilk
Copy link

Small typo with https://gist.github.com/suryart/7418454#gistcomment-2584737
correct file name is app/views/partials/_flash.html.erb (mind the underscore)

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