iTranslated by AI
Introducing flash_unified: A Gem for Unified Handling of Rails Flash Messages on Server and Client
In my previous article, I wrote about the idea of handling Flash messages uniformly from both the server side and client side.
Simply put, it aims to solve the following two points:
- Display Flash messages from the client side using the same representation as the server side.
- Display Flash messages even in Turbo Frame.
I'd like you to refer to the previous article for the mechanism and background, but implementing it turned out to be quite labor-intensive.
However, I was able to package it into a Gem that anyone can easily try, so this time I'll introduce that Gem flash_unified. If you have similar issues, please give it a try. (And I'd appreciate your feedback.)
Quick Start
This article introduces the minimal setup for verifying the functionality. Since Flash messages are handled on both the server and client sides, configuration is needed on both ends.
1. Installation
Install the Gem:
$ gem install flash_unified
If you are using Bundler, add gem 'flash_unified' to your Gemfile and run bundle install.
2. Setup (Client Side)
JavaScript is implemented as ES Modules. Edit config/importmap and pin all.bundle.js as follows:
pin 'flash_unified/all', to: 'flash_unified/all.bundle.js'
Then import it in your entry point (e.g., app/javascript/application.js):
import 'flash_unified/all';
If you are not using importmap-rails and are using an asset pipeline like Sprockets, you can set it up similarly by adding the following in the <head> section of your HTML:
For Asset Pipeline
<link rel="modulepreload" href="<%= asset_path('flash_unified/all.bundle.js') %>">
<script type="importmap">
{
"imports": {
"flash_unified/all": "<%= asset_path('flash_unified/all.bundle.js') %>"
}
}
</script>
<script type="module">
import 'flash_unified/all';
</script>
3. Setup (Server Side)
Edit your view layout and place the helper flash_unified_sources right after the <body> tag:
<body>
<%= flash_unified_sources %>
...
This outputs invisible elements, so the layout will not break. This helper outputs the source data for displaying Flash messages, such as server-side messages and templates.
Then, place the helper flash_container where you want Flash messages to appear:
<div class="notify">
<%= flash_container %>
...
That's basically it.
When updating only a part of the page with Turbo Frame or Turbo Stream, you need to set up a way to deliver Flash messages to the partially updated area.
-
Turbo Frame
Place the helper
flash_storageinside the frame:<turbo-frame id="foo"> <%= flash_storage %> ... -
Turbo Stream
Add the output of the following helper to one of the streams:
<%= flash_turbo_stream %>
Note that setting Flash messages in the controller remains the same as before; no changes are needed for this Gem:
# No changes needed for the Gem
if @item.save
redirect_to @item, notice: "Created successfully."
else
flash.now[:alert] = "Could not create."
render :new, status: :unprocessable_content
end
That's all for the setup. Restart your server and check if Flash messages are displayed as expected.
Template Customization
The Flash message elements rendered by default have no styling, so customize them by applying any CSS you like. Also, the displayed Flash message elements remain on the page, so implement a close/dismiss functionality as needed.
Key points:
- Set the
idof the<template>element toflash-message-template-${type}. Replace$typewith the Flash type, such asinfo,warning, oralert. - Place an element with the CSS class name
flash-message-textinside that template. The message text will be inserted there.
The template is placed in:
- app/views/flash_unified/_templates.html.erb
You can generate a skeleton with the generator:
$ bin/rails generate flash_unified:install --template
Alternatively, instead of placing a template file, you can override the helper method def flash_templates. This helper method simply renders the template file, so if you make the helper generate the tags directly, you can omit the template file.
For example, a version styled with Tailwind CSS:
def flash_templates
# Override flash_unified view helper
def flash_templates
templates = [
{
id: 'alert',
text_color: 'text-red-700',
bg_color: 'bg-red-100'
},
{
id: 'notice',
text_color: 'text-blue-700',
bg_color: 'bg-blue-100'
},
{
id: 'warning',
text_color: 'text-yellow-700',
bg_color: 'bg-yellow-100'
}
]
safe_join(
templates.map do |tpl|
content_tag(:template, id: "flash-message-template-#{tpl[:id]}") do
content_tag(:div,
content_tag(:span, '', class: 'flash-message-text'),
class: "p-4 mb-4 text-sm rounded-lg #{tpl[:text_color]} #{tpl[:bg_color]}",
role: 'alert',
data: { controller: 'dismissable' }
)
end
end
)
end
And here is an example Stimulus controller "dismissable" referenced above. This controller adds a "×" button at the top right of the element, and clicking it removes the element itself:
dismissable_controller.js
import { Controller } from '@hotwired/stimulus'
export default class extends Controller {
connect() {
const closeButton = document.createElement('button');
closeButton.innerHTML = '×';
closeButton.setAttribute('type', 'button');
closeButton.setAttribute('aria-label', 'Close');
closeButton.className = 'absolute top-2 right-2 text-gray-700 hover:text-gray-900';
closeButton.addEventListener('click', () => this.dismiss());
this.element.classList.add('relative');
this.element.appendChild(closeButton);
}
dismiss() {
this.element.remove();
}
}
(Optional) Displaying Network Errors
Inside all.bundle.js, there is a helper feature for displaying Flash messages from the client side when a network error occurs.
For example, when a server error is returned in response to a Turbo form submission, an event listener detects it and the event handler automatically displays an error message corresponding to the HTTP status code as a Flash message.
This feature is disabled by default, so to use it, set the following data attribute:
<html data-flash-unified-enable-network-errors="true">
The messages displayed at this time are defined in the I18n locale translation files:
- config/locales/http_status_messages.en.yml
- config/locales/http_status_messages.ja.yml
To customize them, place a file and edit the text. You can generate a skeleton with the generator:
$ bin/rails generate flash_unified:install --locale
Advanced Usage
The flash_unified/all.bundle.js used in the Quick Start automatically registers several event listeners upon import. It is designed as an "all-in-one" solution, convenient for simple demo sites or small-scale admin panels.
Of course, it also supports cases where you need custom control without relying on the automatic setup. In such cases, you will need to implement additional setup and event registration (calling render methods).
In any case, the details are documented in the Gem's documentation, so please refer to that. Here, I will list and introduce the topics briefly.
Custom Renderer
You can replace the template rendering process with any custom function. For example, you can integrate with third-party notification libraries like Notyf.
import { setFlashMessageRenderer } from 'flash_unified';
setFlashMessageRenderer((messages) => {
const notyf = new Notyf();
messages.forEach(({ type, message }) => {
const level = type === 'info' || type === 'notice' ? 'success' : 'error';
notyf.open({ type: level, message });
});
});
Container Selection
By default, Flash messages formatted by the template are inserted into all container elements, even if there are multiple display targets (container elements).
To limit to specific container elements, you can either create a custom renderer or set HTML data attributes.
<html
data-flash-unified-container-first-only="true"
data-flash-unified-container-sort-by-priority="true"
data-flash-unified-container-visible-only="true">
Custom Events
You can display messages by receiving the custom event flash-unified:messages.
document.dispatchEvent(new CustomEvent('flash-unified:messages', {
detail: { messages: [ { type: 'alert', message: 'The operation was canceled.' } ] }
}));
Continue on GitHub
That concludes the introduction of the basic usage.
This Gem is developed on GitHub. The repository contains more detailed documentation than this article, as well as developer documentation. Also, if you clone the repository, you can immediately try out a Rails app located in test/dummy. If you are interested, please check it out.
Discussion