Turbo Frames on Rails

Turbo, part of the Hotwire tripartite, gives you the tools to write dramatically less custom JavaScript than you would otherwise need to build modern, performant web applications.

Turbo is composed of Turbo Drive, Turbo Frames, Turbo Streams, and Turbo Native. Each is a valuable piece of the puzzle but today we’re going to focus on Turbo Frames.

Turbo Frames “allow predefined parts of a page to be updated on request.” Used wisely, frames allow developers to decompose their UI into independently updated pieces, quickly.

Why should I use Turbo Frames?

Turbo Frames unlock a huge amount of potential with minimal changes to existing code and they can be gradually introduced to existing projects without necessitating major architectural changes.

In greenfield projects designed with Turbo Frames in mind, a small team of developers can use frames to deliver fast, efficient user interfaces in dramatically less time than would be required when build a SPA-powered front end.

While Turbo Frames can be used with many different tech stacks, Rails developers will find the tight integration of frames into Rails (via the turbo-rails gem) makes using frames in Rails a breeze.

The Turbo documentation gap

As with many new technologies, one of the barriers to getting started with Turbo Frames is inconsistent/incomplete documentation. Along with problems in the official documentation, much of the tutorial content written about Turbo Frames is already out of date.

Turbo has evolved quickly since its release in December of 2020, and the documentation and supporting tutorials from content creators have struggled to keep pace.

As an example of the documentation gap, turbo-rails doesn’t have any dedicated usage documentation, instead just linking to the base Turbo docs and letting users figure out the rest.

This means that learning to use Turbo Frames in your Rails application today often requires reading the docs, then digging through source code, and then Googling your way through Github issues and forum posts. Turbo Frames can be difficult to approach.

In time the documentation will improve and the community will coalesce around best practices and standards that can be more easily communicated to new users.

In the meantime, here we are.

Read the rest 24-minute read

Sort tables (almost) instantly with Ruby on Rails and Turbo Frames

One of the wonderful things about working in Rails in 2021 is that we are spoiled for options when it comes to building modern, reactive applications. When we need to build highly interactive user experiences, we don’t need to reach for JavaScript frameworks like Vue or React — the Rails ecosystem has all the tools we need to deliver exceptionally fast, efficient, and easy-to-maintain front ends.

Yesterday, I published an article demonstrating a simple implementation of a sortable table with StimulusReflex. Today, we’re going to build the same experience with Turbo Frames instead.

Why build the same thing with two different tools? Because we have great options to choose from in Rails-land, and understanding each option is a great place to start when considering which tool is right for you and your team.

Like yesterday, our application is going to allow users to view a table of players. They’ll be able to click on each header cell to sort the table in ascending and descending order.

Sorting will happen very quickly, without a full-page turn, and we won’t be writing any custom JavaScript or doing anything outside of writing ordinary Ruby code and ERB templates.

When we’re finished, the application will work like this:

A screen recording of a user clicking on column headers on a data table. With each click, the table sorts itself by that column and a triangle indicator appears next to the column used for sorting

You can demo the application for yourself on Heroku (the free dyno might need a moment to wake up when you visit it) or view the complete source on Github.

This article assumes that you are comfortable building applications with Ruby on Rails and may be difficult to follow if you have never worked with Rails before. Previous experience with Turbo Frames is not required.

Let’s get started!

Read the rest 21-minute read

Sort tables (almost) instantly with Ruby on Rails and StimulusReflex

Today we’re going to use Ruby on Rails and StimulusReflex to build a table that sorts itself each time a user clicks on a header column.

Sorting will occur without a page turn, in less than 100ms, won’t require any custom JavaScript, and we’ll build the whole thing with regular old ERB templates and a little bit of Ruby.

The end result will be very fast, efficient, simple to reason about, and easy to extend as new functionality is required.

It’ll be pretty fancy.

When we’re finished, it will work like this:

A screen recording of a user clicking on column headers on a data table. With each click, the table sorts itself by that column and a triangle indicator appears next to the column used for sorting

You can view the finished product on Heroku, or find the full source on Github.

This article will be most useful to folks who are familiar with Ruby on Rails, but you will not need any previous experience with Stimulus or StimulusReflex to follow along. If you’ve never worked with Rails before, some concepts here may be a little tough to follow.

Let’s get started!

Read the rest 26-minute read

Server-rendered modal forms on Rails with CableReady, Mrujs, Stimulus, and Tailwind

The Rails ecosystem continues to thrive, and Rails developers have all the tools they need to build modern, reactive, scalable web applications quickly and efficiently. If you care about delivering exceptional user experiences, your options in Rails-land have never been better.

Today we’re going to dive into this ecosystem to use two cutting edge Rails projects to allow users to submit forms that are rendered inside of a modal.

The form will open in a modal with content populated dynamically by the server, the server will process the form submission, and the DOM will updated without a full-page turn.

To accomplish this, we’ll use Stimulus for the front-end interactivity, CableReady’s brand new CableCar feature to send content back from the server, and Mrujs to enable AJAX requests and to automatically process CableCar’s operations.

It’ll be pretty fancy.

When we’re finished, our application will look like this:

A screen recording of an initially empty web page with a header that reads Customers and a link to create new customers. The user clicks on the new customer link adn a pop-up modal displays on the screen. The user types in a name, creating a customer and the page updates automatically with the new customer's inforamtion. The user continues to add and update a few more customer records, each time the form opens in a modal and the page updates with the user's change immediately.

This article includes a fair amount of JavaScript and assumes a solid understanding of the basics of Ruby on Rails.

If you’ve never used Rails before, this article might move a little too quickly for you. While comfort with Rails and JavaScript are needed, you don’t need to have any prior experience with CableReady or Stimulus.

As usual, you can find the complete source code for this article on Github.

Let’s dive in!

Read the rest 31-minute read

Doing the Impossible — Building a Persistent Audio Player in Ruby on Rails

Today we’re going to learn how to build a Ruby on Rails app that accomplishes what some folks think is impossible in a multi-page application — persisting an audio player while navigating around an application.

We’ll use Ruby on Rails and Turbo to accomplish this, but we could use Turbo’s predecessor, Turbolinks to achieve the same result, and Rails is only incidental to the finished project. We could just as easily use Turbo with any other “multi-page” framework and deliver the same experience.

When we’re finished, our application will allow users to create and manage Ideas along with a persistent audio player tuned to a white noise internet radio station, to help them focus while they generate ideas.

Users will be able to start and stop the audio using a standard <audio> input. When audio is playing, it will continue playing as the user navigates around the application.

The application will look like this:

A screen recording of a web page. On the web page is an audio player and interface to create and view Ideas. The user clicks play on the audio player and then navigates through pages of the idea management interface. While they navigate, the audio player continues playing.

After we’ve built our application, we’ll spend a time talking about myths in web development, and how to avoid falling into the expert-led myth-trap.

This article assumes basic familiarity with Ruby on Rails, but no prior experience with Turbo is required, and you should be able to follow along even if you’ve never seen Rails code before.

Let’s get started.

Read the rest Eight-minute read

Building a Live Search Experience with StimulusReflex and Ruby on Rails

As we approach the release of Rails 7, the Rails ecosystem is full of options to build modern web applications, fast. Over the last 9 months, I’ve written articles on building type-as-you-search interfaces with Stimulus and with the full Hotwire stack, exploring a few of the options available to Rails developers.

Today, we’re going to build a live search experience once more. This time with StimulusReflex, a “new way to craft modern, reactive web interface with Ruby on Rails”. StimulusReflex relies on WebSockets to pass events from the browser to Rails, and back again, and uses morphdom to make efficient updates on the client-side.

When we’re finished, our application will look like this:

A screen recording of a user on a web page with a list of player names below a search text box. The user types 'Dirk' in the search box and the list of player names is automatically filtered based on the search term. The user clicks a clear search link and the list of players resets while the text box is cleared.

It won’t win any beauty contests, but it will give us a chance to explore a few of the core concepts of StimulusReflex.

As we work, you will notice some conceptual similarities between StimulusReflex and Turbo Streams, but there are major differences between the two projects, and StimulusReflex brings functionality and options that don’t exist in Turbo.

Before we get started, this article will be most useful for folks who are comfortable with Ruby on Rails and who are new to StimulusReflex. If you prefer to skip ahead to the source for the finished project, you can find the full code that accompanies this article on Github.

Let’s dive in.

Read the rest 22-minute read

Building a Real Time Scoreboard with Ruby on Rails and CableReady

The release of Hotwire in late 2020 brought attention to a growing interest within the Rails community in building modern, reactive Rails applications without needing the complexity of an API + SPA.

Although Hotwire’s Turbo library garnered a lot of attention, the Rails community has been working for years to improve the toolset we have to build modern, full-stack Rails applications. Turbo isn’t the first attempt at giving Rails developers the tools they need.

One of the most important of these projects is CableReady, which powers StimulusReflex and Optimism, along with standing on its own as a tool to:

Create great real-time user experiences by triggering client-side DOM changes, events and notifications over ActionCable web sockets

Source: CableReady Welcome

Today we’re going to explore CableReady by using Rails, CableReady, and Stimulus to build a scoreboard that updates for viewers in real-time, with just a few lines of Ruby and JavaScript.

When we’re finished, our scoreboard will look like this:

A screen recording of a user with a web page and a terminal window open. On the page are the scores for two teams, Miami and Dallas. The user types a command in the terminal to update the home team's score to 95 and, after the command runs, the score on the web page for Miami updates to 95.

This article assumes that you’re comfortable working with Rails but you won’t need any prior knowledge of CableReady or ActionCable to follow along. If you’ve never used Rails before, this article isn’t the best place to start.

Let’s dive in!

Read the rest 19-minute read

Conditional Rendering With Turbo Stream Broadcasts

A very common pattern in Rails development is for a view to contain checks for things like current_user.can?(:take_some_action). These types of checks are common, especially in B2B applications that implement role-based permissions powered by a solution like Pundit.

So, naturally, when a Rails developer begins working with Turbo Stream broadcasts, they wonder how to access the current_user or other session-level variables. The short answer? You can’t.

Partials rendered via a stream broadcast have to be free of global variables or they’ll throw an error because they are not rendered within the context of a specific request. Without that request context variables like current_user will always be undefined.

While we can’t access global variables from a broadcast, we can, with creative use of Turbo Frames, still deliver real-time broadcasts that retain access to key variables like current_user.

To demonstrate the concept today we’re going to build a simple application that displays a list of Spies.

Each spy will have a mission; however, not everyone will be able to see the spy’s mission. Only visitors with secret clearance can see the mission field. Everyone else will see a “Classified” string in place of the mission.

When a new spy is created, we’ll broadcast an update to any viewers of the spy list. Viewers with clearance will see the mission for the newly created spy, viewers without won’t.

The end result will work like this:

A screen recording of a user with two windows open to the same webpage. The webpage displays a list of names, with a header that reads Spies. In one window the user sees a message that they have secret clearance, in the other they don't. The user creates a new spy by entering a name and the new spy ges added to the list of spies already on the page. In the window with secret clearance, the user sees newly created spy's mission, in the other, they don't.

This article will be most useful for folks who are already comfortable with Ruby on Rails and who have a little experience with Turbo already. If you’re comfortable with Rails but you’ve never used Turbo before, an article like this might be a better introduction.

As usual, you’ll find the full code for this article on GitHub.

Ready? Let’s get started.

Read the rest 18-minute read

Turbo Streams on Rails

Turbo, part of the Hotwire tripartite, helps you build modern, performant web applications with dramatically less custom JavaScript.

Turbo is composed of Turbo Drive, Turbo Frames, Turbo Streams, and Turbo Native. Each is a valuable piece of the puzzle but today we’re going to focus on Turbo Streams.

Turbo Streams “deliver page changes over WebSocket, Server-Sent Events, or in response to form submissions” and they might be the most exciting part of the Turbo package.

Streams allow you to deliver fast and efficient user experiences with minimal effort and, for Rails developers, you’ll find that streams fit comfortably into your existing toolkit.

With just a few lines of code, you can send tiny snippets of HTML over the wire and and use those snippets to update the DOM with no custom JavaScript.

For fancier use cases, you can broadcast changes over a WebSocket connection to keep every interested user updated without a refresh. No custom JavaScript to write, just HTML and a little bit of Ruby.

What’s missing?

One of the challenges of new web development tools is that documentation can be sparse, and that’s no different with Hotwire and Turbo.

Official documentation exists, and the introduction video demoing Hotwire does a good job showing how Hotwire works, but comprehensive guides and documentation clearly outlining the various options you have when using Hotwire aren’t all the way there yet.

Streams are powerful but, with limited documentation, getting up to speed can be daunting.

So, today I’m going to share a bit of what I’ve learned from using Turbo Streams in a variety of applications, from small experiments to production-grade applications, to help you get value from Turbo Streams in your Rails application faster.

Read the rest 17-minute read

Instant search with Rails and Hotwire

Last year I wrote an article on building an instant search form with Rails and Stimulus. Since then, Turbo, the other half of Hotwire for the web has been released and the Hotwire stack is now the default for new applications in Rails 7.

Turbo opens the door for an even simpler, cleaner implementation of an instant search form.

So, today we’re taking another look at how to build a search-as-you-type interface that allows us to query our database for matches and update the UI with those matches (almost) instantly.

When we’re done, our code will look almost identical to what you’re used to writing to build Rails applications, and the only JavaScript we’ll need will be to trigger form submissions as the user types.

The finished product will work like this:

A screen recording of a user typing in a word to search a list of Dallas Mavericks basketball players. As they type, the list of players updates automatically.

I’m writing this assuming that you’re comfortable with Ruby on Rails - you won’t need any knowledge of the Hotwire stack and you’ll find the most value from this article if you’re new to Turbo. While this article uses Stimulus, its core focus is on Turbo, and specifically how to use Turbo Frames in a Rails application.

You can find the complete code for this guide on Github. Follow along with this guide from the main branch, or see the complete implementation in the instant search branch.

Let’s get started.

Read the rest 19-minute read