Muhammad Faisal Iqbal
Muhammad Faisal Iqbal

Reputation: 1836

To handle flash messages types dynamically

I want to display flash messages in different styles

i.e for :success message "alert alret-suceess"

I 'm using this code in layout to handle them dynamically

<% flash.each do |type, msg| %>
    <%= content_tag :div, msg,class: "alert alert-#{type}" %>
<% end %>

But it works fine for success message giving green background but for "notice" and "alert" types, it gives white background. I 'm suppose to handle them with if else condition or there is any better way available.

Upvotes: 1

Views: 1879

Answers (1)

Rob Wise
Rob Wise

Reputation: 5120

This is a similar approach to my answer here: https://stackoverflow.com/a/31095573/3259320

helpers/alert_helper.rb

module AlertHelper
  def build_alert_classes(alert_type)
    classes = 'alert alert-dismissable '
    case alert_type.to_sym 
    when :alert, :danger, :error, :validation_errors
        classes += 'alert-danger'
    when :warning, :todo
        classes += 'alert-warning'
    when :notice, :success
        classes += 'alert-success'
    else 
        classes += 'alert-info'
    end
  end
end

Then in your view, it would become this:

view

<% flash.each do |type, msg| %>
    <%= content_tag :div, msg, class: build_alert_classes(type) %>
<% end %>

Upvotes: 2

Related Questions