-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathslides_rails_websockets.html
More file actions
774 lines (724 loc) · 42.7 KB
/
slides_rails_websockets.html
File metadata and controls
774 lines (724 loc) · 42.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Slides for
Rails Websockets — Ruby on Rails Guides
</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" data-turbo-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print">
<link rel="stylesheet" type="text/css" href="stylesheets/highlight.css" data-turbo-track="reload">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="stylesheets/reset.css">
<link rel="stylesheet" href="stylesheets/reveal.css">
<link rel="stylesheet" href="stylesheets/myslide.css" id="theme">
<link rel="stylesheet" href="stylesheets/code.css">
<script src="javascripts/clipboard.js" data-turbo-track="reload"></script>
<script src="javascripts/slides.js" data-turbo-track="reload"></script>
</head>
<body>
<div class="reveal">
<!-- Any section element inside of this container is displayed as a slide -->
<div class="slides">
<section>
<h1>Rails Websockets</h1><p>While HTTP only allows requests from the client sent to the server,
websockets offer a permanent connection between client and server.
With Actioncable you can use websockets for publish-subscribe communication.</p><p>By referring to this guide, you will be able to:</p>
<ul>
<li>Build a chat app in your webapp</li>
<li>Incorporate "server push" functionality in your app</li>
</ul>
<div class="interstitial repo"><p>You can study the <a href="https://github.com/backend-development/rails_websockets">code</a> and try out <a href="https://stepstones.herokuapp.com/">the demo</a> for the example app described here.</p></div>
<p><small>Slides - use arrow keys to navigate, esc to return to page view, f for fullscreen</small></p>
</section>
<p>TBD</p><section><a class='slide_break' href='rails_websockets.html#slide-0'>▻</a>
<h2 id="websockets"><a class="anchorlink" href="#websockets"><span>1</span> Websockets</a></h2><p>Websockets are built on top of HTTP and HTTPS:</p>
<ul>
<li>they reuse the default ports 80 and 443</li>
<li>they start out as a normal HTTP request</li>
<li>they reuse cookies</li>
</ul>
<p>but after the initial request, a websocket turns into
a permanent connection between the server and the client.</p><div class="interstitial code">
<pre><code class="highlight plaintext">GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Origin: http://example.com
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Sec-WebSocket-Protocol: chat
</code></pre>
<button class="clipboard-button" data-clipboard-text="GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Origin: http://example.com
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Sec-WebSocket-Protocol: chat
">Copy</button>
</div>
<p>Both the client and the server can send messages across
the websocket at any time. Both the client and the
server should be able to handle incoming messages at any time.</p></section>
<section><a class='slide_break' href='rails_websockets.html#slide-1'>▻</a>
<h2 id="publish-subscribe"><a class="anchorlink" href="#publish-subscribe"><span>2</span> Publish-Subscribe</a></h2><p>In Rails we have to distinguish three concepts:</p>
<ul>
<li>The websocket <strong>connection</strong> deals with authenticating a user
<ul>
<li>see <code>app/channels/application_cable/connection.rb</code></li>
<li>see <code>app/assets/javascripts/cabel.js</code></li>
</ul></li>
<li>A <strong>channel</strong>
<ul>
<li>see <code>app/channels/*_channel.rb</code></li>
<li>see <code>app/assets/javascripts/channels/*.js</code></li>
</ul></li>
<li>A <strong>stream</strong> inside a channel
<ul>
<li>inside each channel streams are identified by a string</li>
</ul></li>
</ul>
<p>In our example app we will be using:</p>
<ul>
<li>a ChatChannel with one stream,
<ul>
<li>the stream is identified by <code>room: main</code></li>
</ul></li>
<li>an AdventureChannel with one stream per adventure, for example
<ul>
<li>a stream identified by <code>url_path: /adventures/1</code></li>
<li>a stream identified by <code>url_path: /adventures/2</code></li>
<li>a stream identified by <code>url_path: /adventures/3</code></li>
</ul></li>
</ul>
</section>
<section><a class='slide_break' href='rails_websockets.html#slide-2'>▻</a>
<h2 id="chat-example"><a class="anchorlink" href="#chat-example"><span>3</span> Chat Example</a></h2><p>In our example app several users should be able to chat with each other,
no matter which page of the app they are currently viewing.</p><p><img src="images/chat-screenshot-annotated.png" alt="Screenshot of the Chat Area on the Homepage"></p><p>We will build the app starting from the client side:</p></section>
<section><a class='slide_break' href='rails_websockets.html#slide-3'>▻</a>
<h3 id="client-connects-and-subscribes"><a class="anchorlink" href="#client-connects-and-subscribes"><span>3.1</span> Client connects and subscribes</a></h3><p>The javascript concerning websockets is stored in the
file <code>app/assets/javascripts/cabel.js</code> which was created
by rails. It should look like this:</p><div class="interstitial code">
<pre><code class="highlight javascript"><span class="c1">//= require action_cable</span>
<span class="c1">//= require_self</span>
<span class="c1">//= require_tree ./channels</span>
<span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
<span class="k">this</span><span class="p">.</span><span class="nx">App</span> <span class="o">||</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">App</span> <span class="o">=</span> <span class="p">{});</span>
<span class="nx">App</span><span class="p">.</span><span class="nx">cable</span> <span class="o">=</span> <span class="nx">ActionCable</span><span class="p">.</span><span class="nf">createConsumer</span><span class="p">();</span>
<span class="p">}).</span><span class="nf">call</span><span class="p">(</span><span class="k">this</span><span class="p">);</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="//= require action_cable
//= require_self
//= require_tree ./channels
(function() {
this.App || (this.App = {});
App.cable = ActionCable.createConsumer();
}).call(this);
">Copy</button>
</div>
<p>and which in turn includes the folder <code>app/assets/javascripts/channels</code>
where we will store our own javascript. </p><p>To connect each user to the chat channel, we add a new file
<code>app/assets/javascripts/channels/chat.js</code>:</p><div class="interstitial code">
<pre><code class="highlight javascript"><span class="nx">App</span><span class="p">.</span><span class="nx">chatChannel</span> <span class="o">=</span> <span class="nx">App</span><span class="p">.</span><span class="nx">cable</span><span class="p">.</span><span class="nx">subscriptions</span><span class="p">.</span><span class="nx">create</span><span class="p">({</span>
<span class="na">channel</span><span class="p">:</span> <span class="dl">'</span><span class="s1">ChatChannel</span><span class="dl">'</span><span class="p">,</span>
<span class="na">room</span><span class="p">:</span> <span class="dl">'</span><span class="s1">main</span><span class="dl">'</span>
<span class="p">}</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="App.chatChannel = App.cable.subscriptions.create({
channel: 'ChatChannel',
room: 'main'
}
">Copy</button>
</div>
<p>This Javascript code also depends on one meta-tag being set in the webpage:</p><div class="interstitial code">
<pre><code class="highlight plaintext"><meta name="action-cable-url" content="/cable" />
</code></pre>
<button class="clipboard-button" data-clipboard-text="<meta name="action-cable-url" content="/cable" />
">Copy</button>
</div>
<p>Do not write this by hand, use the rails helper in the
file <code>app/views/layouts/application.html.erb</code>:</p><div class="interstitial code">
<pre><code class="highlight plaintext"><%= action_cable_meta_tag %>
</code></pre>
<button class="clipboard-button" data-clipboard-text="<%= action_cable_meta_tag %>
">Copy</button>
</div>
<p>Now the client tries to connect to the websocket at URL <code>/cable</code>
and then subscribe to the chat channel.
If you open your app in the browser now, you should
see an error in the developer tools console:</p><div class="interstitial code">
<pre><code class="highlight plaintext">WebSocket connection to 'ws://localhost:3000/cable' failed: Error during WebSocket handshake: Unexpected response code: 500
</code></pre>
<button class="clipboard-button" data-clipboard-text="WebSocket connection to 'ws://localhost:3000/cable' failed: Error during WebSocket handshake: Unexpected response code: 500
">Copy</button>
</div>
<p>So the client is trying to connect, but it does not work yet.</p></section>
<section><a class='slide_break' href='rails_websockets.html#slide-4'>▻</a>
<h3 id="server-accepts-and-authentication"><a class="anchorlink" href="#server-accepts-and-authentication"><span>3.2</span> Server accepts and Authentication</a></h3><p>The server side code is stored in the folder <code>app/channels</code>. We first
take a look at <code>app/channels/application_cable/connection.rb</code>, which was
created by rails:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="k">module</span> <span class="nn">ApplicationCable</span>
<span class="k">class</span> <span class="nc">Connection</span> <span class="o"><</span> <span class="no">ActionCable</span><span class="o">::</span><span class="no">Connection</span><span class="o">::</span><span class="no">Base</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="module ApplicationCable
class Connection < ActionCable::Connection::Base
end
end
">Copy</button>
</div>
<p>Remember that the server side code concerning websocket is not
called by a controller. So even if we already built authentication
into our app, and added code for <code>current_user</code> to <code>application_controller.rb</code>,
the <code>current_user</code> will not be available here in the ApplicationCable.</p><p>But we do have access to cookies in Actioncable:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="k">module</span> <span class="nn">ApplicationCable</span>
<span class="k">class</span> <span class="nc">Connection</span> <span class="o"><</span> <span class="no">ActionCable</span><span class="o">::</span><span class="no">Connection</span><span class="o">::</span><span class="no">Base</span>
<span class="n">identified_by</span> <span class="ss">:current_user</span> <span class="c1"># creates a instance variable</span>
<span class="k">def</span> <span class="nf">connect</span>
<span class="no">Rails</span><span class="p">.</span><span class="nf">logger</span><span class="p">.</span><span class="nf">warn</span><span class="p">(</span><span class="s2">"this is the info I read from the cookie:"</span><span class="p">)</span>
<span class="no">Rails</span><span class="p">.</span><span class="nf">logger</span><span class="p">.</span><span class="nf">warn</span><span class="p">(</span><span class="n">cookies</span><span class="p">.</span><span class="nf">encrypted</span><span class="p">[</span><span class="no">Rails</span><span class="p">.</span><span class="nf">application</span><span class="p">.</span><span class="nf">config</span><span class="p">.</span><span class="nf">session_options</span><span class="p">[</span><span class="ss">:key</span><span class="p">]])</span>
<span class="nb">self</span><span class="p">.</span><span class="nf">current_user</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">find</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">disconnect</span>
<span class="c1"># Any cleanup work needed when the cable connection is cut.</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user # creates a instance variable
def connect
Rails.logger.warn("this is the info I read from the cookie:")
Rails.logger.warn(cookies.encrypted[Rails.application.config.session_options[:key]])
self.current_user = User.find(3)
end
def disconnect
# Any cleanup work needed when the cable connection is cut.
end
end
end
">Copy</button>
</div>
<p>After adding this code the browser should be able to connect to
the websocket. In Firefox with the extension <strong>Websocket Monitor</strong> you
can see the messages sent across the websocket in a separate tab:</p><p><img src="images/ws_firefox.png" alt="Websocket in Firefox with Extension Websocket Monitor"></p><p>You can see that there is more going on than just the subscription
that we initiated from the client side.</p><p>On the server side you will see the connection in the log file:</p><div class="interstitial code">
<pre><code class="highlight plaintext">Started GET "/cable" for ::1 at 2017-01-25 17:45:09 +0100
Started GET "/cable/" [WebSocket] for ::1 at 2017-01-25 17:45:09 +0100
Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: keep-alive, Upgrade, HTTP_UPGRADE: websocket)
this is the info I read from the cookie:
{"session_id"=>"b8ee74d5afe32d5", "_csrf_token"=>"9mBRsEoGnRnkkW6", "user_id"=>"3"}
</code></pre>
<button class="clipboard-button" data-clipboard-text="Started GET "/cable" for ::1 at 2017-01-25 17:45:09 +0100
Started GET "/cable/" [WebSocket] for ::1 at 2017-01-25 17:45:09 +0100
Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: keep-alive, Upgrade, HTTP_UPGRADE: websocket)
this is the info I read from the cookie:
{"session_id"=>"b8ee74d5afe32d5", "_csrf_token"=>"9mBRsEoGnRnkkW6", "user_id"=>"3"}
">Copy</button>
</div>
<p>We successfully decoded the session data from the encrypted cookie, you can see
that the <code>user_id</code> is 3 in this case. We can use this to set the <code>current_user</code> correctly:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="k">module</span> <span class="nn">ApplicationCable</span>
<span class="k">class</span> <span class="nc">Connection</span> <span class="o"><</span> <span class="no">ActionCable</span><span class="o">::</span><span class="no">Connection</span><span class="o">::</span><span class="no">Base</span>
<span class="n">identified_by</span> <span class="ss">:current_user</span> <span class="c1"># creates a instance variable</span>
<span class="k">def</span> <span class="nf">connect</span>
<span class="n">session_from_cookie</span> <span class="o">=</span> <span class="n">cookies</span><span class="p">.</span><span class="nf">encrypted</span><span class="p">[</span><span class="no">Rails</span><span class="p">.</span><span class="nf">application</span><span class="p">.</span><span class="nf">config</span><span class="p">.</span><span class="nf">session_options</span><span class="p">[</span><span class="ss">:key</span><span class="p">]]</span>
<span class="n">user_id</span> <span class="o">=</span> <span class="n">session_from_cookie</span><span class="p">[</span><span class="s1">'user_id'</span><span class="p">]</span>
<span class="n">reject_unauthorized_connection</span> <span class="k">if</span> <span class="n">user_id</span><span class="p">.</span><span class="nf">nil?</span>
<span class="nb">self</span><span class="p">.</span><span class="nf">current_user</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">find</span><span class="p">(</span><span class="n">user_id</span><span class="p">)</span>
<span class="no">Rails</span><span class="p">.</span><span class="nf">logger</span><span class="p">.</span><span class="nf">warn</span><span class="p">(</span><span class="s2">"connection for user </span><span class="si">#{</span><span class="n">current_user</span><span class="si">}</span><span class="s2">"</span><span class="p">)</span>
<span class="n">reject_unauthorized_connection</span> <span class="k">if</span> <span class="n">current_user</span><span class="p">.</span><span class="nf">nil?</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">disconnect</span>
<span class="c1"># Any cleanup work needed when the cable connection is cut.</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user # creates a instance variable
def connect
session_from_cookie = cookies.encrypted[Rails.application.config.session_options[:key]]
user_id = session_from_cookie['user_id']
reject_unauthorized_connection if user_id.nil?
self.current_user = User.find(user_id)
Rails.logger.warn("connection for user #{current_user}")
reject_unauthorized_connection if current_user.nil?
end
def disconnect
# Any cleanup work needed when the cable connection is cut.
end
end
end
">Copy</button>
</div>
<p>After this, a user that has logged in to the rails app
is automatically also logged in to the websocket, as you
can see in the log file:</p><div class="interstitial code">
<pre><code class="highlight plaintext">Started GET "/cable" for ::1 at 2017-01-25 17:54:51 +0100
Started GET "/cable/" [WebSocket] for ::1 at 2017-01-25 17:54:51 +0100
Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: keep-alive, Upgrade, HTTP_UPGRADE: websocket)
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 3], ["LIMIT", 1]]
connection for user Brigitte Jellinek
Registered connection (Z2lkOi8vc3RlcHN0b25lcy9Vc2VyLzM)
ChatChannel is transmitting the subscription confirmation
ChatChannel is streaming from chat_main
</code></pre>
<button class="clipboard-button" data-clipboard-text="Started GET "/cable" for ::1 at 2017-01-25 17:54:51 +0100
Started GET "/cable/" [WebSocket] for ::1 at 2017-01-25 17:54:51 +0100
Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: keep-alive, Upgrade, HTTP_UPGRADE: websocket)
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 3], ["LIMIT", 1]]
connection for user Brigitte Jellinek
Registered connection (Z2lkOi8vc3RlcHN0b25lcy9Vc2VyLzM)
ChatChannel is transmitting the subscription confirmation
ChatChannel is streaming from chat_main
">Copy</button>
</div>
<p>Now the server is ready to receive data from this client and send data to this client.</p></section>
<section><a class='slide_break' href='rails_websockets.html#slide-5'>▻</a>
<h3 id="client-sends-data"><a class="anchorlink" href="#client-sends-data"><span>3.3</span> Client sends data</a></h3><p>To implement the chat we can use the already existing HTML in application.html.erb:</p><div class="interstitial code">
<pre><code class="highlight plaintext"><section id="chat" class="holder" style="display:none;">
<div id="output">
<p>Chat...</p>
</div>
<div id="input">
<span><%= current_user %>: </span>
<input name="chat" type="text">
<input type="button" value="send">
</div>
</section>
</code></pre>
<button class="clipboard-button" data-clipboard-text="<section id="chat" class="holder" style="display:none;">
<div id="output">
<p>Chat...</p>
</div>
<div id="input">
<span><%= current_user %>: </span>
<input name="chat" type="text">
<input type="button" value="send">
</div>
</section>
">Copy</button>
</div>
<p>We just have to make it visible as soon as we have a websocket connection.
We change <code>app/assets/javascripts/channels/chat.js</code>, adding a second
argument to subscriptions.create: an object that holds a <code>connected</code>-function:</p><div class="interstitial code">
<pre><code class="highlight plaintext">// create(channelName, mixin)
App.chatChannel = App.cable.subscriptions.create({
channel: 'ChatChannel',
room: 'main'},
{
connected: function() {
$('#chat').show();
}
}
);
</code></pre>
<button class="clipboard-button" data-clipboard-text="// create(channelName, mixin)
App.chatChannel = App.cable.subscriptions.create({
channel: 'ChatChannel',
room: 'main'},
{
connected: function() {
$('#chat').show();
}
}
);
">Copy</button>
</div>
<p>If a user types something into the chat-input field and
presses enter or the send button, we want the text to
be sent across the websocket:</p><div class="interstitial code">
<pre><code class="highlight plaintext">$(function() {
function send_chat() {
var text = $('#input input[name=chat]').val();
$('#input input[name=chat]').val('');
App.chatChannel.send({ body: text });
}
$('#input input[name=chat]').on('keypress',function (e) {
if (e.which == 13 || e.keyCode == 13) {
send_chat();
}
});
$('#input input[type=button]').on('click', send_chat);
});
</code></pre>
<button class="clipboard-button" data-clipboard-text="$(function() {
function send_chat() {
var text = $('#input input[name=chat]').val();
$('#input input[name=chat]').val('');
App.chatChannel.send({ body: text });
}
$('#input input[name=chat]').on('keypress',function (e) {
if (e.which == 13 || e.keyCode == 13) {
send_chat();
}
});
$('#input input[type=button]').on('click', send_chat);
});
">Copy</button>
</div>
<p>If you type in 'Hello' and send it, you can see the message
being sent in the websocket tab of firefox developer tools:</p><p><img src="images/ws_firefox_send.png" alt="chat message being sent to the server"></p></section>
<section><a class='slide_break' href='rails_websockets.html#slide-6'>▻</a>
<h3 id="server-receives-data"><a class="anchorlink" href="#server-receives-data"><span>3.4</span> Server receives data</a></h3><p>Right now the server does not know how to handle the incoming data,
in the log file you will read:</p><div class="interstitial code">
<pre><code class="highlight plaintext">Unable to process ChatChannel#receive({"body"=>"hello"})
</code></pre>
<button class="clipboard-button" data-clipboard-text="Unable to process ChatChannel#receive({"body"=>"hello"})
">Copy</button>
</div>
<p>We implement <code>receive</code> in <code>app/channels/chat_channel.rb</code>:</p><div class="interstitial code">
<pre><code class="highlight plaintext">class ChatChannel < ApplicationCable::Channel
# Called when the consumer has successfully
# become a subscriber of this channel.
def subscribed
stream_from "chat_#{params[:room]}"
end
def receive(data)
data["user"] = current_user.full_name
data["time"] = Time.now.strftime('%H:%M')
ActionCable.server.broadcast("chat_#{params[:room]}", data)
end
end
</code></pre>
<button class="clipboard-button" data-clipboard-text="class ChatChannel < ApplicationCable::Channel
# Called when the consumer has successfully
# become a subscriber of this channel.
def subscribed
stream_from "chat_#{params[:room]}"
end
def receive(data)
data["user"] = current_user.full_name
data["time"] = Time.now.strftime('%H:%M')
ActionCable.server.broadcast("chat_#{params[:room]}", data)
end
end
">Copy</button>
</div>
<p>Here we take the data coming in from the client
and add some more: the name of the current user and
the current time on the server.</p><p>The <code>broadcast</code> method will send the new data to
all users subscribed to the chat-channel, even
the user who originally sent it.</p></section>
<section><a class='slide_break' href='rails_websockets.html#slide-7'>▻</a>
<h3 id="chat-example-client-recieves-data"><a class="anchorlink" href="#chat-example-client-recieves-data"><span>3.5</span> Client recieves data</a></h3><p>In `<code>app/assets/javascripts/channels/chat.js</code>, where
we made the subscription, we add a function to handle
the received data:</p><div class="interstitial code">
<pre><code class="highlight javascript"><span class="nx">App</span><span class="p">.</span><span class="nx">chatChannel</span> <span class="o">=</span> <span class="nx">App</span><span class="p">.</span><span class="nx">cable</span><span class="p">.</span><span class="nx">subscriptions</span><span class="p">.</span><span class="nf">create</span><span class="p">({</span>
<span class="na">channel</span><span class="p">:</span> <span class="dl">'</span><span class="s1">ChatChannel</span><span class="dl">'</span><span class="p">,</span>
<span class="na">room</span><span class="p">:</span> <span class="dl">'</span><span class="s1">main</span><span class="dl">'</span><span class="p">},</span>
<span class="p">{</span>
<span class="na">received</span><span class="p">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span> <span class="p">{</span>
<span class="nf">$</span><span class="p">(</span><span class="dl">"</span><span class="s2">#output</span><span class="dl">"</span><span class="p">).</span><span class="nf">append</span><span class="p">(</span>
<span class="dl">'</span><span class="s1"><p></span><span class="dl">'</span> <span class="o">+</span> <span class="nx">data</span><span class="p">[</span><span class="dl">'</span><span class="s1">user</span><span class="dl">'</span><span class="p">]</span> <span class="o">+</span> <span class="dl">'</span><span class="s1">: </span><span class="dl">'</span> <span class="o">+</span> <span class="nx">data</span><span class="p">[</span><span class="dl">'</span><span class="s1">body</span><span class="dl">'</span><span class="p">]</span> <span class="o">+</span> <span class="dl">'</span><span class="s1"></p></span><span class="dl">'</span>
<span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">);</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="App.chatChannel = App.cable.subscriptions.create({
channel: 'ChatChannel',
room: 'main'},
{
received: function(data) {
$("#output").append(
'<p>' + data['user'] + ': ' + data['body'] + '</p>'
);
}
}
);
">Copy</button>
</div>
</section>
<section><a class='slide_break' href='rails_websockets.html#slide-8'>▻</a>
<h2 id="progress-example"><a class="anchorlink" href="#progress-example"><span>4</span> Progress Example</a></h2><p>For the second example the communication structure is a bit more complex:
All the users <em>in one adventure</em> should see each other progress through the steps.</p><p><img src="images/adventures-screenshot-annotated.png" alt="Screenshot of the Adventure Page"></p><p>The page displays the adventure and the three steps it consists of.</p><p>The currently logged in user is 'Brigitte Jellinek'. Her progress is described
at the top of the page (purple box) as "You are currently working on step 2.".
A blue cursor just above step 2 also indicates this.</p><p>At every step we can see the status of all users. For example at the 2nd step,
in the green box, we can see the status of four users. We can see
that Alyssa P. Hacker is blocked.</p><p>Inside the yellow box we find the interface the current user can use to change
their status at step 2.</p><p>We will use websockets to communicate changes to all users. So if Alyssa changes
her status from blocked to finished, the server will send websocket messages to
all the other users currently viewing the page, and their display will change
accordingly.</p><p>Contrast this to a classic web app built with HTTP requests, where you would
need to reload the page to get the new status. </p></section>
<section><a class='slide_break' href='rails_websockets.html#slide-9'>▻</a>
<h3 id="client-subscribes"><a class="anchorlink" href="#client-subscribes"><span>4.1</span> Client subscribes</a></h3><p>There is no need to change anything in <code>app/assets/javascripts/cabel.js</code>. We
add another file to the channels folder <code>app/assets/javascripts/channels/adventure.js</code>:</p><div class="interstitial code">
<pre><code class="highlight plaintext">App.cable.subscriptions.create({ channel: "AdventureChannel" })
</code></pre>
<button class="clipboard-button" data-clipboard-text="App.cable.subscriptions.create({ channel: "AdventureChannel" })
">Copy</button>
</div>
<p>In <code>channels/chat.js</code> we also set a room when creating the subscription,
and we used the same room for all users. This time we want to treat users
who are working on different adventures differently.</p><p>One simple way of doing this is to supply the URL of the current page
as a parameter when creating the subscription:</p><div class="interstitial code">
<pre><code class="highlight plaintext">App.adventureChannel = App.cable.subscriptions.create({
channel: "AdventureChannel",
url_path: document.location.pathname
});
</code></pre>
<button class="clipboard-button" data-clipboard-text="App.adventureChannel = App.cable.subscriptions.create({
channel: "AdventureChannel",
url_path: document.location.pathname
});
">Copy</button>
</div>
<p>The path is communicated via websocket:</p><p><img src="images/subscribe_adventure.png" alt="Websocket in Firefox with Extension Websocket Monitor"></p></section>
<section><a class='slide_break' href='rails_websockets.html#slide-10'>▻</a>
<h3 id="server-accepts"><a class="anchorlink" href="#server-accepts"><span>4.2</span> Server accepts</a></h3><p>On the server side we create a new file <code>app/channels/adventure_channel.rb</code>:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">AdventureChannel</span> <span class="o"><</span> <span class="no">ApplicationCable</span><span class="o">::</span><span class="no">Channel</span>
<span class="k">def</span> <span class="nf">subscribed</span>
<span class="n">stream_from</span> <span class="s1">'/adventures/4'</span> <span class="c1"># TODO: read param url_path</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="class AdventureChannel < ApplicationCable::Channel
def subscribed
stream_from '/adventures/4' # TODO: read param url_path
end
end
">Copy</button>
</div>
<p>We only want to send out messages to users who are viewing on
of the adventure-pages, not to people who are on the homepage or anywhere
else.</p><p>So we analyze the <code>url_path</code> parameter we recive from the client,
and only <code>stream_from</code> if the path fits:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="k">def</span> <span class="nf">subscribed</span>
<span class="k">if</span> <span class="n">params</span><span class="p">[</span><span class="ss">:url_path</span><span class="p">]</span> <span class="o">=~</span> <span class="sr">%r{^/adventures/</span><span class="se">\d</span><span class="sr">+$}</span>
<span class="n">stream_from</span> <span class="n">params</span><span class="p">[</span><span class="ss">:url_path</span><span class="p">]</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="def subscribed
if params[:url_path] =~ %r{^/adventures/\d+$}
stream_from params[:url_path]
end
end
">Copy</button>
</div>
</section>
<section><a class='slide_break' href='rails_websockets.html#slide-11'>▻</a>
<h3 id="progress-example-client-recieves-data"><a class="anchorlink" href="#progress-example-client-recieves-data"><span>4.3</span> Client recieves data</a></h3><p>To help with debugging the channel while we are building it,
we will copy over any data recived by the client to the chat window:</p><div class="interstitial code">
<pre><code class="highlight javascript"><span class="nx">App</span><span class="p">.</span><span class="nx">adventureChannel</span> <span class="o">=</span> <span class="nx">App</span><span class="p">.</span><span class="nx">cable</span><span class="p">.</span><span class="nx">subscriptions</span><span class="p">.</span><span class="nf">create</span><span class="p">({</span>
<span class="na">channel</span><span class="p">:</span> <span class="dl">"</span><span class="s2">AdventureChannel</span><span class="dl">"</span><span class="p">,</span>
<span class="na">url_path</span><span class="p">:</span> <span class="nb">document</span><span class="p">.</span><span class="nx">location</span><span class="p">.</span><span class="nx">pathname</span>
<span class="p">},</span>
<span class="p">{</span>
<span class="na">received</span><span class="p">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span> <span class="p">{</span>
<span class="nf">$</span><span class="p">(</span><span class="dl">"</span><span class="s2">#output</span><span class="dl">"</span><span class="p">).</span><span class="nf">append</span><span class="p">(</span><span class="dl">'</span><span class="s1"><p></span><span class="dl">'</span> <span class="o">+</span> <span class="nx">data</span><span class="p">.</span><span class="nx">description</span> <span class="o">+</span> <span class="dl">'</span><span class="s1"></p></span><span class="dl">'</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">});</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="App.adventureChannel = App.cable.subscriptions.create({
channel: "AdventureChannel",
url_path: document.location.pathname
},
{
received: function(data) {
$("#output").append('<p>' + data.description + '</p>');
}
});
">Copy</button>
</div>
</section>
<section><a class='slide_break' href='rails_websockets.html#slide-12'>▻</a>
<h3 id="server-sends-data-if-status-changes"><a class="anchorlink" href="#server-sends-data-if-status-changes"><span>4.4</span> Server sends data if status changes</a></h3><p>Every time a user changes their status we want the server
to send out messages. The model where the status is stored
is <code>Step</code>. ActiveRecord supplies hooks for <a href="https://guides.rubyonrails.org/active_record_callbacks.html#transaction-callbacks">callbacks</a> we can use here:</p><div class="interstitial code">
<pre><code class="highlight plaintext">class Step < ApplicationRecord
delegate :url_helpers, to: 'Rails.application.routes'
after_create_commit :notify_adventure_channel
after_update_commit :notify_adventure_channel
def notify_adventure_channel
ActionCable.server.broadcast(
url_helpers.adventure_path(stepstone.adventure),
description: describe_new_state
)
end
</code></pre>
<button class="clipboard-button" data-clipboard-text="class Step < ApplicationRecord
delegate :url_helpers, to: 'Rails.application.routes'
after_create_commit :notify_adventure_channel
after_update_commit :notify_adventure_channel
def notify_adventure_channel
ActionCable.server.broadcast(
url_helpers.adventure_path(stepstone.adventure),
description: describe_new_state
)
end
">Copy</button>
</div>
<p>The <code>ActionCable.server.broadcast</code> methods takes one string argument
for identifying the stream to broadcast on. We used the
path to the adventure page, for example <code>"/adventure/3"</code>. Here
we use a helper to contruct this string, we could also have
done it directly with <code>"/adventure/#{stepstone.adventure_id}"</code>.</p><p>With these pieces in place a change in status should already
appear in the chat window.</p></section>
<section><a class='slide_break' href='rails_websockets.html#slide-13'>▻</a>
<h3 id="client-recieves-data-partial-as-html"><a class="anchorlink" href="#client-recieves-data-partial-as-html"><span>4.5</span> Client recieves data: partial as html</a></h3><p>The display of all the users status involves a lot of html and
additional resources.</p><p><img src="images/adventures-screenshot-show-status.png" alt="partial show_status"></p><p>There is already a separate partial to handle this, it is
called in the <code>adventures/show.html.erb</code> view repeatedly:</p><div class="interstitial code">
<pre><code class="highlight plaintext"><% @stepstones.each_with_index do |stepstone, i| %>
<div id="step_<%= i %>">
<h2>
<span class="number"><%= (i + 1).ordinalize %>.</span> Step
</h2>
...
<article>
....
<div id="step_<%= i %>_show_status" class="step_show_status">
<%= render 'stepstones/show_status', stepstone: stepstone, i: i %>
</div>
</article>
</div>
<% end %>
</code></pre>
<button class="clipboard-button" data-clipboard-text="<% @stepstones.each_with_index do |stepstone, i| %>
<div id="step_<%= i %>">
</section>
<section><a class='slide_break' href='rails_websockets.html#slide-14'>▻</a>
<h2>
<span class="number"><%= (i + 1).ordinalize %>.</span> Step
</h2>
...
<article>
....
<div id="step_<%= i %>_show_status" class="step_show_status">
<%= render 'stepstones/show_status', stepstone: stepstone, i: i %>
</div>
</article>
</div>
<% end %>
">Copy</button>
</div>
<p>We can reuse the <code>stepstones/show_status</code> partial on the server side,
when we send the message to the websocket. And we can reuse the
<code>div</code> with id <code>step_3</code> on the client side, when we incorpoarte the
recieved html into the page. </p><p>We will add two new keys to the message, which now looks like this:</p><div class="interstitial code">
<pre><code class="highlight plaintext">{
"description": "Alyssa P. Hacker is now blocked at the 2nd step.",
"selector": "#step_1_show_status",
"html" : "<div class=\"user blocked\"><span><img...> ....</div>\n"
}
</code></pre>
<button class="clipboard-button" data-clipboard-text="{
"description": "Alyssa P. Hacker is now blocked at the 2nd step.",
"selector": "#step_1_show_status",
"html" : "<div class=\"user blocked\"><span><img...> ....</div>\n"
}
">Copy</button>
</div>
<p>On the server we add another key/value pair to message:</p><div class="interstitial code">
<pre><code class="highlight plaintext"> def notify_adventure_channel
ActionCable.server.broadcast(
url_helpers.adventure_path(stepstone.adventure),
description: describe_new_state,
selector: "#step_#{i}_show_status",
html:
ApplicationController.renderer.render(
partial: 'stepstones/show_status',
locals: { stepstone: stepstone, i: i }
)
)
end
</code></pre>
<button class="clipboard-button" data-clipboard-text=" def notify_adventure_channel
ActionCable.server.broadcast(
url_helpers.adventure_path(stepstone.adventure),
description: describe_new_state,
selector: "#step_#{i}_show_status",
html:
ApplicationController.renderer.render(
partial: 'stepstones/show_status',
locals: { stepstone: stepstone, i: i }
)
)
end
">Copy</button>
</div>
<p>on the client we just use jQuery to replace the html inside
the div:</p><div class="interstitial code">
<pre><code class="highlight plaintext">received: function(data) {
$(data.selector).html(data.html);
$("#output").append('<p>' + data.description + '</p>');
}
</code></pre>
<button class="clipboard-button" data-clipboard-text="received: function(data) {
$(data.selector).html(data.html);
$("#output").append('<p>' + data.description + '</p>');
}
">Copy</button>
</div>
<p>Now the status-display with all the users should work!</p></section>
<section><a class='slide_break' href='rails_websockets.html#slide-15'>▻</a>
<h2 id="deployment"><a class="anchorlink" href="#deployment"><span>5</span> Deployment</a></h2></section>
<section><a class='slide_break' href='rails_websockets.html#slide-16'>▻</a>
<h2 id="see-also"><a class="anchorlink" href="#see-also"><span>6</span> See Also</a></h2>
<ul>
<li><a href="https://tools.ietf.org/html/rfc6455">RFC 6455</a></li>
<li><a href="https://blog.ably.io/rails-5-actioncable-the-good-and-bad-parts-1b56c3b31404#.nhzs3q1qd">O'Riordan(2016) Rails ActionCable — The good and bad parts</a> - a good overview of the uses and limitation of ActionCable</li>
</ul>
</div></section>
</div>
</div>
<!-- End slides. -->
<!-- Required JS files. -->
<script src="javascripts/reveal.js"></script>
<script src="javascripts/search.js"></script>
<script src="javascripts/markdown.js"></script>
<script>
// Also available as an ES module, see:
// https://revealjs.com/initialization/
Reveal.initialize({
controls: false,
progress: true,
center: false,
hash: true,
// The "normal" size of the presentation, aspect ratio will
// be preserved when the presentation is scaled to fit different
// resolutions. Can be specified using percentage units.
width: 1000,
height: 600,
disableLayout: false,
// Factor of the display size that should remain empty around
// the content
margin: 0.05,
// Bounds for smallest/largest possible scale to apply to content
minScale: 0.2,
maxScale: 10.0,
keyboard: {
27: () => {
// do something custom when ESC is pressed
var new_url = window.location.pathname.replace('slides_', '') + window.location.hash.replace('/','slide-');
window.location = new_url;
},
191: 'toggleHelp',
13: 'next', // go to the next slide when the ENTER key is pressed
},
// Learn about plugins: https://revealjs.com/plugins/
plugins: [ RevealSearch, RevealMarkdown ]
});
</script>
</body>
</html>