Skip to content

rdsngit/hotwire-turbo-rails-demo

Repository files navigation

Hotwire Turbo for Ruby on Rails with Dracula Theme

This is a Ruby on Rails web app to demo the use of the front-end libraries View Components and Hotwire Turbo.

Hotwire is built into Rails 8 as part of its front-end frameowrk. The Turbo part of Hotwire can be used to update parts of webpages using HTML and websockets. View components are objects for Ruby on Rails views that render to HTML. You can read more about the libraries at the links below:

It uses the topic theme of Dracula as this is the name of a popular Dev tool colour theme: https://draculatheme.com/

Setup

Install the Ruby version in the .ruby-version file then run the terminal command bundle install.

Run the web app

Using the terminal navigate to the root of the project directory and run the command:

bin/dev

Then open your internet browser, such as Chrome, and visit http://localhost:3000/

Click on the buttons on the webpage to see the Dracula themed imaged replaced using the Hotwire library.

Run the tests

The test library used is the rspec-rails gem.

Use the terminal command bin/rspec to run the tests for the view components and see the test output.

$ bin/rspec

ButtonComponent
  renders a button with the specified label, link and params

ImageComponent
  renders an image tag with the specified file

Dracula
  GET /dracula
    renders the Dracula novel image
  POST /dracula/image
    with params image: 'novel'
      renders a turbo steam containing the Dracula novel image
    with params image: 'castle'
      renders a turbo steam containing the Dracula castle image

Finished in 0.03688 seconds (files took 0.59829 seconds to load)
5 examples, 0 failures

Front-end libraries used

Ruby on Rails View Components

The guide to the view components library for Ruby on Rails apps can be found at: https://viewcomponent.org/guide

In this demo app:

Example image view component rendered in demo app image view partial:

<turbo-frame id="dracula_image">
<%= render ImageComponent.new(file: local_assigns[:file]) %>
</turbo-frame>

Hotwire Turbo

Turbo frames updated using the morph refresh method: https://turbo.hotwired.dev/handbook/page_refreshes#morphing

<meta name="turbo-refresh-method" content="morph">

When the DraculaController's #image action is sent a POST request with a param for one of images it will respond turbo_stream.replace with the rendered image generated from the view partial:

format.turbo_stream do
render turbo_stream: turbo_stream.replace(
'dracula_image',
partial: 'dracula/image',
locals: { file: image_file }
)
end

Request specs for the Dracula GET and POST requests and turbo stream responses are located in:

Image sources

Screenshots

Screenshot with image of Dracula novel Screenshot with image of Dracula castle

About

A demo app using the Hotwire Turbo and View Components Front-End libraries for Ruby on Rails

Topics

Resources

Stars

Watchers

Forks