Decorating flash messages in Rails views

Jiří Procházka
Aug 29, 2017 · 1 min read

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!

Code Rocket

Blog of CodeRocket (.co)

)
Jiří Procházka

Written by

Ruby on Rails rider, founder of CodeRocket.co and co-founder of Vinito.cz

Code Rocket

Blog of CodeRocket (.co)

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade