Ruby on Rails Flash messages with Bootstrap
If you're using Ruby on Rails and Bootstrap originally from Twitter, then you may want to display flash messages with the alert
styles. Here is a quick and easy way of doing so.
You just need to quickly extend application_helper.rb
with the following:
def flash_class(level)
case level
when :notice then "alert alert-info"
when :success then "alert alert-success"
when :error then "alert alert-error"
when :alert then "alert alert-error"
end
end
Now when you call a flash message, you can use the following in your view:
<% flash.each do |key, value| %>
<div class="<%= flash_class(key) %>">
<%= value %>
</div>
<% end %>
And just use:
flash[:success] = "Woohoo!"
As a success or:
flash[:alert] = "Alerting you to the monkey on your car!"
Tada!
Written by James Brooks
Related protips
5 Responses
Or, if you are using twitter-bootstrap-rails
gem, you can simply use bootstrap_flash
helper - https://github.com/seyhunak/twitter-bootstrap-rails#flash-helper
over 1 year ago
·
Nice! And for other frameworks such as Semantic-UI is almost the same. Thanks!
over 1 year ago
·
Since Rails 4.1 it does only work with strings for me, e.g.:
module ApplicationHelper
def flash_class(level)
case level
when 'notice' then "alert alert-info"
when 'success' then "alert alert-success"
when 'error' then "alert alert-danger"
when 'alert' then "alert alert-warning"
end
end
end
over 1 year ago
·
Thanx very simple - very usefull
over 1 year ago
·
Thanks that helped !
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Rails
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#