Add Hotwire to an existing Rails app

Dusty Candland | | cloudsh, ruby, rails, hotwire

Some quick notes on adding Hotwire to an existing Rails applicaiton.

Install Hotwire

It's probably a good idea to upgrade to the latest Rails version first. Then install hotwire-rails. The install directions on GitHub are simple enough. Add the gem and run rails hotwire:install.

It's going to install turbo-rails and stimulus-rails. It will install and setup webpacker, if that's used, otherwise it uses the asset pipeline.

You'll need Redis installed

Fixes

Devise

I'm using Devise and the first thing I noticed was login / signup quit working. Needed to change the turbolinks setup to the new turbo setup. This GoRails: Devise Hotwire Turbo is a great how-to. I'd expect Devise to handle this in the future.

The code for the Devise fix works, but needs to be organized.

In production I got this error:

undefined method 'turbo_stream_from' for #<ActionView::Base:0x0000000004fab0>

This Helpers autoloading issue points to an autoloading problem. The TurboController I added to fix Devise was in the config/initializers/devise.rb. As suggested in the issue, moving that into its own file in app/controllers fixes the autoloading problem in production.

Turbolinks

The install process doesn't add Turbo to the application pack. This issue describes some issues with Webpacker and provides an easy fix.

In app/javascript/packs/application.js, add the following import.

import '@hotwired/turbo-rails'

Search for "turbolinks" in the project and change those to "turbo". Some examples:

-= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload'
-= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload'
+= stylesheet_pack_tag 'application', media: 'all', 'data-turbo-track': 'reload'
+= javascript_pack_tag 'application', 'data-turbo-track': 'reload'
-    document.addEventListener('turbolinks:load', loadChart);
- document.addEventListener('turbolinks:click', unloadChart);
+ document.addEventListener('turbo:load', loadChart);
+ document.addEventListener('turbo:click', unloadChart);
-  script src="https://js.stripe.com/v3/" type="text/javascript" data-turbolinks-track="reload"
+ script src="https://js.stripe.com/v3/" type="text/javascript" data-turbo-track="reload"

Cleanup

Remove any turbolinks code from the app/javascript/packs/application.js file.

Uninstall Turbolinks from the package.js.

yarn remove turbolinks

Webmentions

These are webmentions via the IndieWeb and webmention.io. Mention this post from your site: