Decorating flash messages in Rails views

I like using advanced (I mean “advanced” LOL) patterns in Rails and one really handy is decorator (more in my Enhanced Rails Architecture on Github). For decorating Active Records I’m mostly using Draper gem.

But what if you want decorate such thing as flash messages in views? There is also an easy way to go:

# /app/decorators/message_decorator.rb
class MessageDecorator
attr_reader :msg
  def initialize(key, msg)
@key = key
@msg = msg
  def css
if @key == "alert" || @key == "danger"
elsif @key == "warning"
elsif @key == "info"
elsif @key == "success"

And using it in view:

<% flash.each do |key, msg| item =, msg) %>
<div class="w3-panel <%= item.css %>">
<p><%= item.msg %></p>
<% end %>

Yes, it is simple as that. Ruby is allowing to write another piece of code after the end of the block |key, msg| on the same line.

Do you like it? Clap!