18
Real-Time Rails implementing WebSockets in Rails 5 with Action Cable

Real-Time Rails: Implementing WebSockets in Rails 5 with Action Cable

Embed Size (px)

Citation preview

Real-Time Railsimplementing WebSockets in Rails 5 with Action Cable

The Path to Real-Time

Rails

“dealing with WebSockets

is a pain in the ass” –– DHH

• For 13 years, Campfire, Basecamp's own chatting

application, has been using polling.

• Real-time web gaining ascendancy—developers

and consumers want real-time everything

• Phoenix channels are born

“If you could make WebSockets

easier than polling, why wouldn’t

you do it?”

Introducing…

Action Cable!

What are WebSockets?

• Protocol built on top of TCP. They hold the

connection to the server open so that the server can

send information to the client, without a request

being sent from the client!

How Does Action Cable

Work?• One instance of Action Cable server spins up for every

instance of your application.

• Uses Rack socket hijacking API to take over control of

connections from the application server.

• Uses a channel mounted on a sub-URI of your main

application to stream from certain areas of your

application and broadcast to other areas.

• Redis syncs content across instances of your

application.

Action Cable Channels

Replacing Controllers?!

Part I: Configuring Action

Cable

• Puma

• Redis -> `config/cable.yml`

• Mount Action Cable Server on

`ws://localhost:3000/cable`

• Initiate the client-side consumer to open the

persistent WS connection

Part II: Building Channels

and Subscribers• Define and authorize the connection

• Define the channel and tell it where to stream from

• Define your subscriber and tell it to send data to the

channel

• Teach the channel to receive the data and broadcast it

to its stream

• Teach subscriber to receive data from the stream and

put it on the page

Part III: Refactor

(all the Rails 5!)

• Use an after_create_commit hook to fire a message

broadcast job

• Use Action Controller renderers to render the

message partial and broadcast the resultant HTML.

Resources• https://blog.heroku.com/real_time_rails_implementing_websockets_in_r

ails_5_with_action_cable

• http://www.thegreatcodeadventure.com/rails-5-action-cable-with-

multiple-chatroom-subscriptions/

• https://medium.com/evil-martians/new-feature-in-rails-5-render-views-

outside-of-actions-2fc1181e86a8#.hme92hu9u

• DHH’s Action Cable demo:

https://www.youtube.com/watch?v=n0WUjGkDFS0

• https://github.com/rails/actioncable