Enhancing Your Ruby on Rails Application with Turbo and Stimulus

  • 2024/8/22
  • Enhancing Your Ruby on Rails Application with Turbo and Stimulus はコメントを受け付けていません

Ruby on Rails has always been a powerful framework for building web applications quickly and efficiently. With the introduction of Hotwire , which includes Turbo and Stimulus, Rails developers can now easily create dynamic, responsive web applications without the need for a full-blown JavaScript framework. In this blog, we’ll walk through how to integrate Turbo and Stimulus into a Rails application, demonstrating how to enhance user experience with minimal effort.

What Are Turbo and Stimulus?

  • Turbo: Turbo, a core part of the Hotwire suite, dramatically speeds up Rails applications by eliminating the need for full-page reloads. It does this by enabling seamless page transitions, partial page updates, and background loading of page content.
  • Stimulus: Stimulus is a lightweight JavaScript framework that allows you to sprinkle small, reusable bits of JavaScript functionality into your HTML, enhancing your application’s interactivity without the complexity of a single-page application (SPA).

Step 1: Setting Up Turbo and Stimulus in Rails

Rails makes it easy to get started with Turbo and Stimulus, as they are already included by default in new Rails applications starting from version 6.1 (with Hotwire integrated in Rails 7).

Create a New Rails Application

If you’re starting fresh, create a new Rails app with:

rails new my_app --css=tailwind

cd my_app

Tailwind is optional but recommended for rapid frontend styling. Rails 7+ automatically includes Hotwire, so Turbo and Stimulus are ready to go.

For an Existing Rails Application

If you’re adding Hotwire to an existing Rails app, simply add the following gems to your Gemfile:

gem 'turbo-rails'

gem 'stimulus-rails'

Then, run:

bundle install

rails turbo:install stimulus:install

Step 2: Using Turbo in Rails

Turbo replaces traditional Rails helpers like link_to with enhanced versions that support faster navigation and partial page updates.

Turbo Frames

Turbo Frames allow you to update parts of your page without reloading the entire page. For example, you can wrap a section of your page in a turbo-frame tag to specify which part of the page should be updated after an action.

<%= turbo_frame_tag "posts" do %>

  <%= render @posts %>

<% end %>

Now, any link or form inside this frame will only update the content within the frame, not the whole page.

Turbo Streams

Turbo Streams allow you to broadcast changes to specific parts of the page in real-time. For example, you can create, update, or delete a post and have the changes reflected in the browser without a full reload.

# app/views/posts/create.turbo_stream.erb

<%= turbo_stream.append "posts", partial: "posts/post", locals: { post: @post } %>

This will automatically append the newly created post to the list of posts on the page.

Step 3: Using Stimulus in Rails

Stimulus enhances the interactivity of your Rails application by allowing you to add small, reusable bits of JavaScript functionality.

Creating a Stimulus Controller

Generate a Stimulus controller:

rails generate stimulus hello

This will create a hello_controller.js file in app/javascript/controllers.

Edit the controller to respond to user interactions:

// app/javascript/controllers/hello_controller.js

import { Controller } from "@hotwired/stimulus"

 

export default class extends Controller {

  static targets = ["name"]

 

  greet() {

    alert(`Hello, ${this.nameTarget.value}!`)

  }

}

Use the controller in your Rails views:

<div data-controller="hello">

  <input data-hello-target="name" type="text" placeholder="Enter your name">

  <button data-action="click->hello#greet">Greet</button>

</div>

Now, when the button is clicked, the greet method will be triggered, showing an alert with the entered name.

Step 4: Combining Turbo and Stimulus

Turbo and Stimulus are designed to work seamlessly together in Rails applications. For example, you might want to update a section of your page with Turbo and then add interactivity with Stimulus.

Example: Creating and Editing Posts

Imagine a scenario where you have a list of posts. You want to dynamically add a new post to the list using Turbo Streams, and then allow the user to toggle the visibility of each post’s details using Stimulus.

Create a Post with Turbo Streams:
In your PostsController, you would handle the creation of a post and broadcast the update using Turbo Streams:

def create

  @post = Post.new(post_params)

  if @post.save

    respond_to do |format|

      format.turbo_stream

      format.html { redirect_to posts_path, notice: 'Post was successfully created.' }

    end

  else

    render :new

  end

end

Turbo Stream View:
Create the Turbo Stream view to append the new post:

# app/views/posts/create.turbo_stream.erb

<%= turbo_stream.append "posts", partial: "posts/post", locals: { post: @post } %>

Stimulus Controller for Toggling Details:
Create a Stimulus controller to handle the toggling of post details:

// app/javascript/controllers/toggle_controller.js

import { Controller } from "@hotwired/stimulus"

 

export default class extends Controller {

  static targets = ["details"]

 

  toggle() {

    this.detailsTarget.classList.toggle("hidden")

  }

}

Rails View with Turbo and Stimulus:
Use Turbo and Stimulus together in your view:

<div id="posts">

  <%= turbo_frame_tag "post_#{post.id}" do %>

    <div data-controller="toggle">

      <h2><%= post.title %></h2>

      <p data-toggle-target="details" class="hidden"><%= post.content %></p>

      <button data-action="click->toggle#toggle">Show/Hide Details</button>

    </div>

  <% end %>

</div>

With this setup, when a new post is created, it’s appended to the list in real-time, and users can toggle the visibility of each post’s details with the click of a button.

Conclusion

In this blog, we explored how to integrate Turbo and Stimulus into a Ruby on Rails application to build dynamic, responsive web applications with minimal JavaScript. Turbo helps reduce full-page reloads and enhances user experience with faster navigation and partial page updates, while Stimulus allows you to easily add interactive elements to your pages.

By leveraging Turbo and Stimulus, you can create modern, fast, and interactive Rails applications without the complexity of a single-page application (SPA). Whether you’re building a new Rails app or enhancing an existing one, these tools provide a simple and effective way to deliver a great user experience.

関連記事

カテゴリー:

ブログ

情シス求人

  1. 登録されている記事はございません。
ページ上部へ戻る