百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
H

hotwire-chat

> 后端框架
开源

Hotwire Chat 是一个使用 Hotwire 构建的演示 Ruby on Rails Web 应用程序。

156 stars0 点赞3 次浏览
访问官网GitHub

工具介绍

Hotwire Chat 是一个使用 Hotwire 构建的演示 Ruby on Rails Web 应用程序。

Hotwire Chat

Demo chat web application built in Ruby on Rails with Hotwire. The demo is available at: https://hotwired-chat.herokuapp.com

Table of Contents

  • Creating message
    • Broadcasting created message
  • Editing message
  • Updating message
    • Broadcasting updated message
  • Cancelling message edit
  • Destroying message
    • Broadcasting destroyed message
  • Caching
    • Local time
  • Testing
    • Request specs
    • System specs
  • Deploying to Heroku

Creating message

When message form is submitted to the POST /rooms/1/messages endpoint, the messages#create controller action

ruby
# app/controllers/messages_controller.rb
class MessagesController 
  
    
    
      ...
    
  

which is turbo stream action appending html fragment of newly created message to #messages container element. DOM updates are automatically handled by Turbo javascript on client side. The turbo_stream method used in the controller code is provided by turbo-rails gem.

Broadcasting created message

When visiting a chat room page GET /rooms/1, the client automatically subscribes to the room channel turbo stream via ActionCable web socket. The subscription instruction is included in rooms/show.html.erb view rendered by rooms#show action:

erb

Besides subscription, Turbo will automatically unsubscribe from the channel when navigating away from the room page, for example, when logging out.

All message changes (create, update, destroy) are asynchronously broadcasted to the message's room channel.

ruby
# app/models/message.rb
class Message 
  

On receiving a response containing turbo frame with matching identifier, Turbo replaces the content of the turbo frame:

Turbo javascript automatically detects navigation within turbo frame and translates it into fetch request to GET /messages/371/edit with extra headers Turbo-Frame: message_371 and Accept: text/vnd.turbo-stream.html, text/html, application/xhtml+xml. On server side, turbo-rails detects Turbo-Frame header and optimizes the response to not render application layout.

Updating message

The message edit form is nested under the message turbo frame:

When a user submits the form, the PATCH /messages/371 messages#update endpoint renders the turbo frame with the matching identifier containing the html of the updated message:

ruby
# app/controllers/messages_controller.rb
class MessagesController 
  ...

On receiving the response containing turbo frame with the matching identifier, Turbo replaces the content of the turbo frame:

Broadcasting updated message

Cancelling message edit

Destroying message

Broadcasting destroyed message

Caching

One of the key advantages of building modern web applications with Hotwire is server-side rendered views, which can be efficiently cached to reduce rendering time.

The demo app renders message content with html-pipeline transforming raw text with various filters like markdown, sanitization, emoji into html_safe formatted content:

ruby
# app/services/html_formatter.rb
class HtmlFormatter
  class 

which can be observed in the rails log as follows:

Rendered collection of messages/_message.html.erb [4 / 100 cache hits] (Duration: 221.3ms | Allocations: 62880)

and on the subsequent vist:

Rendered collection of messages/_message.html.erb [100 / 100 cache hits] (Duration: 23.7ms | Allocations: 6292)

Local time

The demo app displays the message's timestamps in local time zone. In order to keep the message partial cache friendly (independent of time zone context), local_time gem is used to render the timestamps in UTC on the server-side:

erb
xml
23 Jan 18:11

The timestamps are then converted with local-time javascript libary into local time zone:

javascript
// app/javascript/application.js
import LocalTime from 'local-time'
LocalTime.start()
xml
23 Jan 19:11

Testing

bin/rspec

See .github/workflows/rspec.yml for example configuration of running tests in GitHub Actions.

Request specs

Turbo client-side automatically sets Accept: text/vnd.turbo-stream.html, text/html, application/xhtml+xml header for fetch requests originating from it. The header is recognized by turbo-rails on the server-side, so it is essential to set this header when writing request specs (aka integration tests) to simulate Turbo requests:

ruby
# spec/requets/messages/create_spec.rb
require 'rails_helper'

describe 'messages#create', type: :request do
  let!(:user) { log_in('matt' )}
  let!(:room) { Room.create!(name: 'dev') }

  let(:message_params) { { content: 'hi!' } }
  subject { post room_messages_path(room_id: room.id), params: { message: message_params }, headers: turbo_stream_headers }

  it 'returns turbo stream appending message' do
    subject

    expect(response).to have_http_status(200)
    assert_select("turbo-stream[action='append'][target='messages']", 1)
  end
end

where turbo_stream_headers is defined as follows:

ruby
# spec/support/turbo_stream_spec_support.rb
module TurboStreamSpecSupport
  def turbo_stream_headers(headers={})
    headers.merge('Accept': %i[ turbo_stream html ].map{ |type| Mime[type].to_s }.join(', '))
  end
end

Link navigations within turbo frame have the extra Turbo-Frame: message_371 header passed by Turbo on the client-side. turbo-rails also recognizes this header to skip rendering of application layout, so corresponding requests specs should resemble it:

…

See spec/requests for more examples.

System specs

System specs (aka system tests) are driven_by(:selenium, using: :headless_chrome) and do not require extra configuration for turbo stream actions delivered over web socket. For example spec/system/receive_message_spec.rb tests user receiving turbo stream append action over the action cable web socket when message is sent by other chat participant:

ruby
# spec/system/receive_message_spec.rb
require 'rails_helper'

describe "receive message", type: :system do
  before do
    driven_by(:selenium, using: :headless_chrome)
  end

  let!(:user) { User.create(name: 'matt') }

  it "shows message" do
    log_in(user.name)

    other_user = User.create!(name: 'adam')
    other_message = Message.create!(room: Room.default_room, author: other_user, content: 'Got it!')
    within('#messages') do
      expect(page).to have_content 'Got it!', count: 1
    end
  end
end

See specs/system directory for more examples.

Deploying to Heroku

The demo app can be deployed to Heroku for testing on Heroku's limited free tier. The Deploy to Heroku button will provision a free Heroku dyno, heroku-postgresql:free, and heroku-redis:free addons: or manually:

bash
  $ heroku create
  $ heroku addons:create heroku-postgresql
  $ heroku addons:create heroku-redis
  $ heroku addons:create rollbar # optional step for error tracking (see config/initializers/rollbar.rb)
  $ heroku config:set WEB_CONCURRENCY=2 # optional step to configure 2 puma worker processes (see config/puma.rb)
  $ git push heroku master
  $ heroku open

Issues· 21 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Rubyhotwirerailsrubystimulus

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类后端框架
定价开源

> 相关工具

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架