Action Cable

So I heard you want to make your Rails application realtime...


+ @HayleyCAnderson

Slides: http://hayleycanderson.github.io/action-cable-intro

First, Some Background

HTTP vs. WebSockets vs. Everything Else

HTTP = Hypertext Transfer Protocol

  • GET, POST, DELETE, etc. are HTTP methods sent by clients
  • A client sends a request, and the server sends a response

WebSockets

  • Allows a bidirectional connection between client and server
  • Both client and server can send and receive data in real time
  • Created by HTTP connection being upgraded, then held open

Everything Else

  • Short Polling - Client periodically sends repeated HTTP requests to the server
  • Long Polling - Server holds open HTTP connections until new data is sent
  • HTTP Streaming - Server holds open HTTP connection and sends data over one connection
  • Server Sent Events - Client opens HTTP connection that can accept push notifications

Rails + Realtime

( Until Rails 5 = 💔 )

  • ActionController::Streaming (sorry, wrong type of streaming)
  • ActionController::Live + Server Sent Events
  • Pusher, Faye, Node, etc.

But now, Action Cable

A fullstack WebSockets implementation built directly into Rails

  • Create channels with classic Rails namespacing
  • Broadcast data from anywhere within application
  • Subscribe views to channels to pick up broadcasted data
  • Retain flexibility but let Rails worry about connections

Let's see it in action!

( Demo )

So what's really behind the magic?

( The short version )

The Server

  • Run separately or mounted as an engine
  • Establishes pubsub connection (Redis or PostgreSQL)
  • Creates an event loop that listens in the background

The Connection

  • Client-side consumer creation initiates connection
  • Consumer make a GET request to server and requests upgrade
  • Server can authorize, identify, and/or accept connection

The Channel

  • Channels are exposed to and called by the client
  • Allows consumer subscription to actual pubsub channel
  • Represents a stateless stream of data accessible to consumer

Questions?

+ @HayleyCAnderson

Slides: http://hayleycanderson.github.io/action-cable-intro


Resources