Hotwire Chat 是一个使用 Hotwire 构建的演示 Ruby on Rails Web 应用程序。
Demo chat web application built in Ruby on Rails with Hotwire. The demo is available at: https://hotwired-chat.herokuapp.com
When message form is submitted to the POST /rooms/1/messages endpoint, the messages#create controller action
# 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.
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:
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.
# 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.
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:
# 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:
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:
# 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)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:
23 Jan 18:11The timestamps are then converted with local-time javascript libary into local time zone:
// app/javascript/application.js
import LocalTime from 'local-time'
LocalTime.start()23 Jan 19:11bin/rspecSee .github/workflows/rspec.yml for example configuration of running tests in GitHub Actions.
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:
# 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
endwhere turbo_stream_headers is defined as follows:
# 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
endLink 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 (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:
# 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.
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:
$ 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,或尚未同步最近议题。