Ruby on Rails has a very convenient way of presenting a dialog for potentially dangerous tasks that require some confirmation before proceeding. All you have to do is add

[code language=”ruby”]
data: {confirm: "Are you sure?"}
[/code]

A problem with those, though, is that most (all?) browsers make the dialogs quite ugly:

Call to Buzz - ugly dialog

For Call to Buzz, I wanted to finally have something better. Thankfully, there’s a very simple solution, as long as you are using Bootstrap: Twitter::Bootstrap::Rails::Confirm. You just add it to your project and the dialog now looks like this:

Call to Buzz - bootstrap dialog

That looks much better, but it’d be nice if it had a nice title, better matching buttons, etc. It’s easy to do by adding some data attributes to the link and the documentation for this gem recommends creating a new method to use instead of link_to when deleting something. I wasn’t very happy with this approach so I resolved it with pure JavaScript so my links remain oblivious to the fact that I’m using this gem:

[code language=”javascript”]
$(document).ready(function () {
$("a[data-confirm]").data({
"confirm-fade": true,
"confirm-title": "Call to Buzz"
});
$("a[data-method=delete]").data({
"confirm-title": "Warning",
"confirm-cancel": "Cancel",
"confirm-cancel-class": "btn-cancel",
"confirm-proceed": "Delete",
"confirm-proceed-class": "btn-danger"
});
});
[/code]

And with that, the dialog now looks like this:

Call to Buzz - much better bootstrap dialog

Update: Later on I wanted to be able to define some extra parameters on a link, such as:

[code language=”ruby”]
data: {confirm: "Are you sure you want to disconnect?", confirm_proceed: "Disconnect"}
[/code]

To achieve that I re-wrote the code that dynamically adds the extra confirm parameters to look like this (this uses jQuery 3, on earlier version you’d have to do confirm-fade instead of confirmFade):

[code language=”javascript”]
$("a[data-confirm]").each(function (_, link) {
var $link = $(link);
var data = $link.data();
data = $.extend({}, {
"confirmFade": true,
"confirmTitle": "Call to Buzz"
}, data);
if ($link.data("method") == "delete") {
data = $.extend({}, {
"confirmTitle": "Warning",
"confirmCancel": "Cancel",
"confirmCancelClass": "btn-cancel",
"confirmProceed": "Delete",
"confirmProceedClass": "btn-danger"
}, data);

}
$link.data(data);
});
[/code]


Share:


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *