Rails Hotwire Magic
Turbocharging Your Rails Apps with Turbo & Stimulus
Ever wonder how some web apps achieve a React-like responsiveness without heavy JavaScript?
Hotwire by Basecamp integrates seamlessly with Rails to offer dynamic, interactive UI tools. This guide will explore Hotwire’s Turbo and Stimulus components and provide practical Rails examples to get you started. So Ready to dive in?
Turbo
Turbo is a set of tools designed to make web pages faster and more interactive. Turbo was introduced as a separate gem, Turbo-Rails, alongside other tools like Stimulus. This setup required additional configuration and integration, as Turbo was not yet part of the Rails core. Turbo has been integrated into Rails 7 more seamlessly. The core framework now includes Turbo Drive, Frames, and Streams, simplifying their usage and providing a more cohesive experience. The three main parts in short as below,
- Turbo Drive: Speeds up page navigation with asynchronous updates
- Turbo Frames: Updates parts of the page dynamically
- Turbo Streams: Provides real-time updates with WebSockets
Turbo Drive
This feature makes navigating between pages faster by using AJAX requests to load new content without fully reloading the page. For instance, when you click on a link, Turbo Drive intercepts the request and replaces the page content, keeping the navigation experience smooth and quick.
# In your Gemfile
gem 'hotwire-rails'
# Rails will handle this automatically if you use turbo-rails gem
# In your application.js
import { Turbo } from "@hotwired/turbo-rails"
<!-- app/views/posts/index.html.erb -->
<%= link_to 'View Post', post_path(@post), data: { turbo_frame: '_top' } %>
Clicking the link will load the post content without a full page reload.
Turbo Frames
Turbo Frames allow you to update parts of a page without a full reload. You can define sections of your page that should be replaced with new content when an action occurs.
# In your Gemfile
gem 'hotwire-rails'
# In your controller
class TasksController < ApplicationController
def create
@task = Task.create(task_params)
respond_to do |format|
format.html { redirect_to tasks_path }
format.turbo_stream # Renders create.turbo_stream.erb
end
end
end
<!-- app/views/tasks/index.html.erb -->
<%= form_with(model: Task.new, data: { turbo_frame: 'tasks' }) do |form| %>
<%= form.text_field :name %>
<%= form.submit 'Add Task' %>
<% end %>
<turbo-frame id="tasks">
<%= render @tasks %>
</turbo-frame>
When a new task is added, only the content inside the tasks
frame will be updated.
Turbo Streams
Turbo Streams enable real-time updates by pushing changes to the page. This is useful for applications that require live updates, like notifications or chat messages.
# In your controller
class MessagesController < ApplicationController
def create
@message = Message.create(message_params)
Turbo::StreamsChannel.broadcast_replace_to "chat_#{params[:chat_id]}", target: "messages", partial: "messages/message", locals: { message: @message }
end
end
// app/javascript/channels/chat_channel.js
import { Turbo } from "@hotwired/turbo-rails"
document.addEventListener("turbo:load", () => {
Turbo.connectStreamSource(new WebSocket("/cable"))
})
<!-- app/views/messages/_message.html.erb -->
<div id="message_<%= message.id %>">
<p><%= message.content %></p>
</div>
Stimulus
Stimulus is a lightweight JavaScript framework designed to work seamlessly with Turbo. It helps you add interactivity to your web pages with minimal JavaScript.
Suppose you have a button that toggles a modal window. Using Stimulus, you can attach a controller to the button and define the behavior for showing or hiding the modal. This allows you to manage dynamic interactions with minimal JavaScript code.
Putting It All Together: A Basic Rails 7 App
Combining Turbo Drive, Frames, Streams, and Stimulus can transform your Rails application into a dynamic, real-time web app.
Let’s take an example with a simple interactive Rails 7 app where users can add comments to a blog post. Using Turbo Frames, the comment list updates without reloading the page. Turbo Streams handle real-time updates for new comments. Stimulus manages interactive features like expanding comment forms or toggling visibility.
Conclusion
Hotwire brings a powerful set of tools to Rails, enhancing user experiences with faster navigation, real-time updates, and simple interactivity. By understanding and implementing Turbo Drive, Frames, Streams, and Stimulus, you can create responsive and engaging web applications that deliver a modern, seamless experience. Happy coding!