Thursday, September 8, 2016

Make a Standard Flash Message Bar with Bootstrap Style in Rails Application

Normally, we have a very simple flash message such as “The data has been saved!” in the top of the browser to tell you the operation is done. It is just a simple text, sometimes we even don’t see it since it is not shining!

Fortunately, we can make a helper method accompany with Bootstrap classes to make it look better. It’s simple, useful and can be used as a standard code base for every project.

Here is how:

1. Add a line of ocde: <%= notice_message %> in

/app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
  :
  :
  <body>
    <div class="container" >
      <%= notice_message %>
      <%= yield %>
    </div>
  </body>
</html>

2. Add a helper method “notice_message” in

/app/helpers/application_helper.rb
module ApplicationHelper
  def notice_message
    alert_types = { notice: :success, alert: :danger }

    close_button_options = { class: "close", "data-dismiss" => "alert", "aria-hidden" => true }
    close_button = content_tag(:button, "×", close_button_options)

    alerts = flash.map do |type, message|
      alert_content = close_button + message

      alert_type = alert_types[type.to_sym] || type
      alert_class = "alert alert-#{alert_type} alert-dismissable"

      content_tag(:div, alert_content, class: alert_class)
    end

    alerts.join("\n").html_safe
  end
end
Once the helper is called, like:
redirect_to @size, notice: 'Size was successfully created.'
The flash notice shows:

No comments:

Post a Comment