confirm dialog with sweetalert2 in Rails 6
To replace javascript confirm dialog with sweetalert2 in Rails 6
Used 75 times
L
Lucius Choi
Usage
If you build Rails 6 projects, you can replace easily the js confirm dialog with sweetalert2 using this template.
Run this command in your Rails app directory in the terminal:
rails app:template LOCATION="https://railsbytes.com/script/X6ksA3"
Template Source
Review the code before running this template on your machine.
run "yarn add sweetalert2"
run "mkdir app/javascript/sweetalert"
run "touch app/javascript/sweetalert/index.js"
inject_into_file "app/javascript/sweetalert/index.js", <<-'JAVASCRIPT'
import swal from "sweetalert2";
import Rails from "@rails/ujs";
Rails.confirm = function (message, element) {
const swalWithBootstrap = swal.mixin({
buttonsStyling: true,
});
swalWithBootstrap
.fire({
html: message,
title: "Polyps.KR",
showCancelButton: true,
confirmButtonText: "예",
cancelButtonText: "아니요",
})
.then((result) => {
if (result.value) {
console.log("sweetalert finished");
element.removeAttribute("data-confirm");
element.click();
}
});
};
JAVASCRIPT
inject_into_file "app/javascript/packs/application.js", after: 'require("channels")' do <<-'JAVASCRIPT'
import "sweetalert"
JAVASCRIPT
end