Decorating flash messages in Rails views

Jiří Procházka
Code Rocket
Published in
1 min readAug 29, 2017

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.rbclass MessageDecorator
attr_reader :msg
def initialize(key, msg)
@key = key
@msg = msg
end
def css
if @key == "alert" || @key == "danger"
"w3-red"
elsif @key == "warning"
"w3-orange"
elsif @key == "info"
"w3-blue"
elsif @key == "success"
"w3-green"
end
end
end

And using it in view:

<% flash.each do |key, msg| item = MessageDecorator.new(key, msg) %>
<div class="w3-panel <%= item.css %>">
<p><%= item.msg %></p>
</div>
<% 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!

--

--