flash_messages with toastr
To display Rails 6 flash messages with a javascript plugin, "toastr.js"
Used 81 times
L
Lucius Choi
Usage
If you use stimulus.js in rails 6, you can use this template and set up easily toastr.js for flash messages. You can adjust the position of message with .toastr-top-right style class, as follows:
.toastr-top-right { top: 10px; right: 10px; }
Run this command in your Rails app directory in the terminal:
rails app:template LOCATION="https://railsbytes.com/script/VqqsGD"
Template Source
Review the code before running this template on your machine.
run "yarn add toastr"
run "touch app/javascript/controllers/flash_controller.js"
inject_into_file 'app/javascript/controllers/flash_controller.js', <<-'JAVASCRIPT'
import { Controller } from "stimulus";
import toastr from "toastr";
export default class extends Controller {
static targets = [];
connect() {
let flash_key = this.data.get("key");
let flash_value = this.data.get("value");
console.log(flash_key, flash_value);
toastr.options = {
debug: false,
positionClass: "toastr-top-right",
onclick: null,
fadeIn: 300,
fadeOut: 1000,
timeOut: 5000,
extendedTimeOut: 1000,
};
switch (flash_key) {
case "notice":
case "success":
toastr.success(flash_value);
break;
case "info":
toastr.info(flash_value);
break;
case "warning":
toastr.warning(flash_value);
break;
case "alert":
case "error":
toastr.error(flash_value);
break;
default:
toastr.success(flash_value);
}
}
}
JAVASCRIPT
inject_into_file 'app/helpers/application_helper.rb', after: 'module ApplicationHelper' do <<-'RUBY'
def flash_messages
capture do
flash.each do |key, value|
concat tag.div(
data: {
controller: :flash, flash_key: key, flash_value: value
}
)
end
end
end
RUBY
end
inject_into_file 'app/views/layouts/application.html.erb', after: ' <body>' do <<-'ERB'
<%= flash_messages %>
ERB
end