Learn how Turbo Frames and Streams enable real-time updates in Rails, enhancing performance and interactivity with minimal setup. Improve user experience and streamline your app. To learn more, click here!
About bluebashco
Bluebash was established in 2018 as a custom software development company specializing in Web Development, Artificial Intelligence (AI), Cloud Infrastructure solutions. We have expertise in healthcare, e-commerce, and ed-tech industries, and our solutions are customized to meet each business's specific needs.
Our primary goal is to help startups and established businesses expand their horizons through innovative technology solutions. We believe in transparency and efficient processes, ensuring that our services are available 24/7, deliveries are always on time, and we maintain quality through time tracking and quality assurance. As a leading software development company, our expertise extends to technologies such as Ruby on Rails, React, UI/UX designs, Langchain, and more. We are ISO Certified and specialize in HL7, FHIR, and HIPAA-compliant solutions, guaranteeing security and regulatory adherence while providing exceptional technology services.
Tag Cloud
https://www.bluebash.co/blog/rails-real-time-updates-turbo-frame-stream/
https://www.bluebash.co/services/ruby-on-rails-development-company
Real-Time Updates in Rails:
Harnessing Turbo Frame and
Turbo Stream
In modern web development, delivering real-time updates in Rails
applications has become essential for creating dynamic and engaging
user experiences. One effective way to achieve this is by utilizing
Turbo Frame and Turbo Stream. If you're looking to implement these
features efficiently, choosing Ruby on Rails development company
can help guide you through the process, from installation to
implementation, covering all the essential concepts in Rails 7.
What is Turbo?
Turbo is a lightweight framework designed for real-time updates in
Rails applications. It leverages the power of WebSockets to push
updates to clients without requiring page reloads. The two key
components that make real-time data streaming possible in Rails 7
are:
● Turbo Frame□ This component wraps sections of your HTML that
you want to update in real-time.
● Turbo Stream□ This component broadcasts changes to Turbo
Frames, ensuring all clients receive updates instantly.
Benefits of Using Turbo Frame and Turbo Stream
1. Improved Performance□ By updating only parts of the page,
Turbo reduces data transfer and processing, resulting in quicker
responses and lower server load.
2. Enhanced User Experience□ Users enjoy seamless interactions
with fewer full-page reloads, making your application feel more
responsive and engaging.
3. Simplified Code□ Turbo simplifies front-end code, reducing the
need for complex JavaScript and AJAX calls.
Key Turbo Stream Actions in Rails
Here’s a detailed look at the key actions available with Turbo Stream
in Rails 7:
● Append□ Adds content at the end of a target element.
Usage□ Adding new items to a list.
Example□ Adding a new comment to a comment section.
● Prepend□ Inserts content at the beginning of a target element.
Usage□ Placing new items at the top of a list.
Example□ Adding a new message to a chat window.
● Replace□ Replaces the content of the target element with new
content.
Usage□ Updating a section of a page.
Example□ Updating user profile details.
● Update□ Updates the content of the target element's inner
HTML.
Usage□ Refreshing parts of a page.
Example□ Updating a score in a live display.
● Remove□ Deletes the target element from the DOM.
Usage□ Removing items that are no longer needed.
Example□ Removing a notification.
Getting Started with Turbo in Rails 7
https://www.bluebash.co/services/hire-ruby-on-rails-developers
Installation
To get started with real-time updates in Rails, ensure your Rails
application is running on Rails 7 or later, as Turbo is integrated into
Rails by default. If you're using an older version, you can manually
install the Turbo gem. If you're looking to leverage the full potential of
Turbo in your projects, it's essential to hire Ruby on Rails developers
who are experienced with the latest Rails updates and Turbo's
powerful features.
To begin, add the turbo-rails gem to your Gemfile:
gem 'turbo-rails'
After updating your Gemfile, run bundle install to install the gem.
Here is the example of Real-time Updates with Turbo Streams
In this example, we'll implement a dynamic blacklisting feature for
customers. Users can blacklist or undo blacklist a customer without
the need for page refresh, thanks to Turbo Streams. Let's walk
through how to set up and implement this feature step by step.
1. Update the Customer View Page
In the view page of customer details , add a section to blacklist or
undo blacklist the customer with the help of turbo frame tag.
<%= turbo_frame_tag :blacklist_button do %>
<%= render partial: "admin/shared/blacklist" %>
<% end %>
2. Define the Route
Define the route for the blacklist action.
config/routes.rb
namespace :admin do
resources :customers, except: [:destroy] do
member do
post :blacklist
end
end
end
3. Create Partial for Blacklist Button
Create a partial to handle the display of the blacklist button.
app/views/admin/shared/_blacklist.html.erb
<% if @customer.blacklist? %>
<%= button_to "Undo Blacklist",
blacklist_admin_customer_path(@customer),
method: :post, class: 'btn btn-solid' %>
<% else %>
<%= button_to "Blacklist",
blacklist_admin_customer_path(@customer),
method: :post, class: 'text-primary px-5 py-2
rounded border' %>
<% end %>
4. Controller Action for Blacklist
Handle the blacklist action in the controller.
app/controllers/admin/customers_controller.rb
def blacklist
respond_to do |format|
if @customer.update(blacklist:
!@customer.blacklist)
format.turbo_stream
else
format.json { render json: @customer.errors,
status:
:unprocessable_entity }
end
end
end
5. Create the Turbo Stream View
Create a Turbo Stream view to handle the update of the blacklist
button.
app/views/admin/customers/blacklist.turbo_stream.erb
Output:
Lazy Loading with Turbo in Rails:
Lazy loading is a design pattern that defers the loading of resources
(such as images, components, or data) until they are actually needed.
In web development, this approach is commonly used to optimize
performance by loading non-critical content only when it becomes
visible (e.g., when the user scrolls to it).
This technique is especially useful for pages with a lot of content or
media, as it reduces the initial load time and improves the user
experience by prioritizing essential elements.
Rails makes lazy-loading easy with its turbo_frame_tag element.
<%= turbo_frame_tag :frame_name, src: src_path,
loading: :lazy do %>
Temporary content while we're loading...
<% end %>
What's going on here?
It's really simple — this Turbo Frame will load the contents of a
different Turbo Frame, and overwrite its current content with the
new content.
The new content comes from a Turbo Frame with a matching
:frame_name, located at the src_path.
By setting loading: :lazy, we can make our Turbo Frame do this
loading lazily. While we're waiting, the contents inside the current
turbo_frame_tag will be displayed.
Pros of Lazy Loading:
● Faster Page Load Times □ Only essential content loads first,
improving performance.
● Reduced Bandwidth Usage □ Saves data by loading resources
only when needed.
● Better User Experience □ Users interact with the page faster
without delays.
● Improved Mobile Performance □ Minimizes resource
consumption on slower networks.
● Lower Server Load □ Reduces unnecessary requests, saving
hosting resources.
Here is the example of Lazy Loading in Rails:
In this example we'll implement lazy loading for list all posts.
1. To create a basic lazy loader, adjust your
posts/index.html.erb to include a turbo_frame_tag
Lazy loading with
Hotwire and Turbo
Frames
<%= turbo_frame_tag :posts_lazy, src:
posts_index_lazy_path, loading:
:lazy do %>
<% end %>
This turbo_frame_tag is going to lazily call the
posts_index_lazy_path route, and try to find another
turbo_frame_tag called :posts_lazy.
2. In your PostsController, you need to add a new controller
action for our view
def index_lazy
@posts = Post.all
end
3. Then we need to map our new Posts#index_lazy controller
action to a route file.
Rails.application.routes.draw do
get 'posts/index_lazy', to: 'posts#index_lazy'
resources :posts
end
4. And finally, we need to create a view for our new
Posts#index_lazy controller action.
<%= turbo_frame_tag :posts_lazy do %>
Count: <%= @posts.count %>
<%= render @posts %>
<% end %>
Output:
Summary:
This setup empowers users to perform blacklisting or undoing of
blacklisting actions for a customer seamlessly, without necessitating a
page refresh. Upon triggering the blacklist or undo blacklist button, an
asynchronous request is dispatched to the server, which updates the
customer's blacklist status and subsequently renders an appropriate
Turbo Stream response to reflect the button's updated state.
By integrating Turbo Frame and Turbo Stream into your Rails 7
application, you can significantly enhance user experience and
application performance through real-time updates. Start
implementing these features today to keep your users engaged and
improve the responsiveness of your application!