-
Notifications
You must be signed in to change notification settings - Fork 0
/
action_cable_overview.html
1220 lines (1119 loc) · 89.2 KB
/
action_cable_overview.html
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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Descripción General de Action Cable — Ruby on Rails Guides</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" data-turbolinks-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print">
<link rel="stylesheet" type="text/css" href="stylesheets/prism/default.css" data-turbolinks-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/prism/rails-guides.css" data-turbolinks-track="reload">
<link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<script src="javascripts/prism.js" data-turbolinks-track="reload"></script>
<script src="javascripts/turbolinks.js" data-turbolinks-track="reload"></script>
<script src="javascripts/guides.js" data-turbolinks-track="reload"></script>
<script src="javascripts/responsive-tables.js" data-turbolinks-track="reload"></script>
<meta property="og:title" content="Descripción General de Action Cable — Ruby on Rails Guides" />
<meta name="description" content="NO LEA ESTE ARCHIVO EN GITHUB, LAS GUÍAS SE PUBLICAN EN https://guides.rubyonrails.org.Descripción General de Action CableEn esta guía, aprenderá cómo funciona Action Cable y cómo usar WebSockets para incorpore funciones en tiempo real en su aplicación Rails.Después de leer esta guía, sabrá: Qué es Action Cable y su integración backend y frontend Cómo configurar Action Cable Cómo configurar canales Configuración de implementación y arquitectura para ejecutar Action Cable" />
<meta property="og:description" content="NO LEA ESTE ARCHIVO EN GITHUB, LAS GUÍAS SE PUBLICAN EN https://guides.rubyonrails.org.Descripción General de Action CableEn esta guía, aprenderá cómo funciona Action Cable y cómo usar WebSockets para incorpore funciones en tiempo real en su aplicación Rails.Después de leer esta guía, sabrá: Qué es Action Cable y su integración backend y frontend Cómo configurar Action Cable Cómo configurar canales Configuración de implementación y arquitectura para ejecutar Action Cable" />
<meta property="og:locale" content="en_US" />
<meta property="og:site_name" content="Ruby on Rails Guides" />
<meta property="og:image" content="https://avatars.githubusercontent.com/u/4223" />
<meta property="og:type" content="website" />
</head>
<body class="guide">
<div>
<!-- <img src="images/edge_badge.png" alt="edge-badge" id="edge-badge" />-->
</div>
<div id="topNav">
<div class="wrapper">
<strong class="more-info-label">Más en <a href="https://rubyonrails.org/">rubyonrails.org:</a> </strong>
<span class="red-button more-info-button">
Más Ruby on Rails
</span>
<ul class="more-info-links s-hidden">
<li class="more-info"><a href="https://weblog.rubyonrails.org/">Blog</a></li>
<li class="more-info"><a href="https://guides.rubyonrails.org/">Guías</a></li>
<li class="more-info"><a href="https://api.rubyonrails.org/">API</a></li>
<li class="more-info"><a href="https://stackoverflow.com/questions/tagged/ruby-on-rails">Pedir Ayuda</a></li>
<li class="more-info"><a href="https://github.com/rails/rails">Contribuir on GitHub</a></li>
</ul>
</div>
</div>
<div id="header">
<div class="wrapper clearfix">
<h1><a href="index.html" title="Guías de Ruby on Rails">Guías de Ruby on Rails </a></h1>
<ul class="nav">
<li><a class="nav-item" href="index.html">Inicio</a></li>
<li class="guides-index guides-index-large">
<a href="index.html" id="guidesMenu" class="guides-index-item nav-item">Index de Guías </a>
<div id="guides" class="clearfix" style="display: none;">
<hr />
<dl class="guides-section-container">
<div class="guides-section">
<dt>Empieza Aqui</dt>
<dd><a href="getting_started.html">Introducción a Rails</a></dd>
</div>
<div class="guides-section">
<dt>Modelos</dt>
<dd><a href="active_record_basics.html">Conceptos básicos de Active Record</a></dd>
<dd><a href="active_record_migrations.html">Migraciones de Active Record</a></dd>
<dd><a href="active_record_validations.html">Validaciones de Active Record</a></dd>
<dd><a href="active_record_callbacks.html">Devolución (callbacks) de Llamadas de Active Record</a></dd>
<dd><a href="association_basics.html">Asociaciones de Active Record</a></dd>
<dd><a href="active_record_querying.html">Interfaz de Consulta de Active Record</a></dd>
</div>
<div class="guides-section">
<dt>Vistas</dt>
<dd><a href="layouts_and_rendering.html">Diseños y Renderizado en Rails</a></dd>
<dd><a href="form_helpers.html">Ayudantes de Formulario de Action</a></dd>
</div>
<div class="guides-section">
<dt>Controladores</dt>
<dd><a href="action_controller_overview.html">Descripción General de Action Controller</a></dd>
<dd><a href="routing.html">Rails Routing Desde el Exterior Hacia Adentro</a></dd>
</div>
<div class="guides-section">
<dt>Otros Componentes</dt>
<dd><a href="active_support_core_extensions.html">Extensiones de Núcleo de Active Support</a></dd>
<dd><a href="action_mailer_basics.html">Conceptos Básicos de Action Mailer</a></dd>
<dd><a href="active_job_basics.html">Conceptos Básicos de Active Job</a></dd>
<dd><a href="active_storage_overview.html">Descripción General de Active Storage</a></dd>
<dd><a href="action_cable_overview.html">Descripción General de Action Cable</a></dd>
</div>
<div class="guides-section">
<dt>Temas Avanzados</dt>
<dd><a href="i18n.html">Rails API de Internacionalización (I18n)</a></dd>
<dd><a href="testing.html">Prueba de Aplicaciones de Rails</a></dd>
<dd><a href="security.html">Seguridad de Aplicaciones Rails</a></dd>
<dd><a href="debugging_rails_applications.html">Depuración de Applications Rails</a></dd>
<dd><a href="configuring.html">Configuración de Aplicaciones de Rails</a></dd>
<dd><a href="command_line.html">La Línea de Comandos de Rails</a></dd>
<dd><a href="asset_pipeline.html">La Canalización de Activos</a></dd>
<dd><a href="autoloading_and_reloading_constants.html">Constantes de Autocarga y Recarga (Zeitwerk Mode)</a></dd>
<dd><a href="autoloading_and_reloading_constants_classic_mode.html">Constantes de Autocarga y Recarga (modo clásico)</a></dd>
<dd><a href="caching_with_rails.html">Almacenamiento en Caché con Rails Descripción General</a></dd>
<dd><a href="api_app.html">Uso de Rails para Aplicaciones Solo API</a></dd>
</div>
<div class="guides-section">
<dt>Extending Rails (toda la sección necesita traducción)</dt>
<dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
<dd><a href="generators.html">Creating and Customizing Rails Generators & Templates</a></dd>
</div>
</dl>
</div>
</li>
<li><a class="nav-item" href="contributing_to_ruby_on_rails.html">Contribuir</a></li>
<li class="guides-index guides-index-small">
<select class="guides-index-item nav-item">
<option value="index.html">Guides Index</option>
<optgroup label="Empieza Aqui">
<option value="getting_started.html">Introducción a Rails</option>
</optgroup>
<optgroup label="Modelos">
<option value="active_record_basics.html">Conceptos básicos de Active Record</option>
<option value="active_record_migrations.html">Migraciones de Active Record</option>
<option value="active_record_validations.html">Validaciones de Active Record</option>
<option value="active_record_callbacks.html">Devolución (callbacks) de Llamadas de Active Record</option>
<option value="association_basics.html">Asociaciones de Active Record</option>
<option value="active_record_querying.html">Interfaz de Consulta de Active Record</option>
</optgroup>
<optgroup label="Vistas">
<option value="layouts_and_rendering.html">Diseños y Renderizado en Rails</option>
<option value="form_helpers.html">Ayudantes de Formulario de Action</option>
</optgroup>
<optgroup label="Controladores">
<option value="action_controller_overview.html">Descripción General de Action Controller</option>
<option value="routing.html">Rails Routing Desde el Exterior Hacia Adentro</option>
</optgroup>
<optgroup label="Otros Componentes">
<option value="active_support_core_extensions.html">Extensiones de Núcleo de Active Support</option>
<option value="action_mailer_basics.html">Conceptos Básicos de Action Mailer</option>
<option value="active_job_basics.html">Conceptos Básicos de Active Job</option>
<option value="active_storage_overview.html">Descripción General de Active Storage</option>
<option value="action_cable_overview.html">Descripción General de Action Cable</option>
</optgroup>
<optgroup label="Temas Avanzados">
<option value="i18n.html">Rails API de Internacionalización (I18n)</option>
<option value="testing.html">Prueba de Aplicaciones de Rails</option>
<option value="security.html">Seguridad de Aplicaciones Rails</option>
<option value="debugging_rails_applications.html">Depuración de Applications Rails</option>
<option value="configuring.html">Configuración de Aplicaciones de Rails</option>
<option value="command_line.html">La Línea de Comandos de Rails</option>
<option value="asset_pipeline.html">La Canalización de Activos</option>
<option value="autoloading_and_reloading_constants.html">Constantes de Autocarga y Recarga (Zeitwerk Mode)</option>
<option value="autoloading_and_reloading_constants_classic_mode.html">Constantes de Autocarga y Recarga (modo clásico)</option>
<option value="caching_with_rails.html">Almacenamiento en Caché con Rails Descripción General</option>
<option value="api_app.html">Uso de Rails para Aplicaciones Solo API</option>
</optgroup>
<optgroup label="Extending Rails (toda la sección necesita traducción)">
<option value="rails_on_rack.html">Rails on Rack</option>
<option value="generators.html">Creating and Customizing Rails Generators & Templates</option>
</optgroup>
</select>
</li>
</ul>
</div>
</div>
<hr class="hide" />
<div id="feature">
<div class="wrapper">
<p><strong>NO LEA ESTE ARCHIVO EN GITHUB, LAS GUÍAS SE PUBLICAN EN <a href="https://guides.rubyonrails.org">https://guides.rubyonrails.org</a>.</strong></p><h2>Descripción General de Action Cable</h2><p>En esta guía, aprenderá cómo funciona Action Cable y cómo usar WebSockets para
incorpore funciones en tiempo real en su aplicación Rails.</p><p>Después de leer esta guía, sabrá:</p>
<ul>
<li>Qué es Action Cable y su integración backend y frontend</li>
<li>Cómo configurar Action Cable</li>
<li>Cómo configurar canales</li>
<li>Configuración de implementación y arquitectura para ejecutar Action Cable</li>
</ul>
<div id="subCol">
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
<ol class="chapters">
<li><a href="#what-is-action-cable-questionmark">What is Action Cable?</a></li>
<li><a href="#terminology">Terminology</a></li>
<li><a href="#what-is-pub-sub-questionmark">What is Pub/Sub?</a></li>
<li>
<a href="#server-side-components">Server-Side Components</a>
<ul>
<li><a href="#server-side-components-connections">Connections</a></li>
<li><a href="#channels">Channels</a></li>
</ul>
</li>
<li>
<a href="#client-side-components">Client-Side Components</a>
<ul>
<li><a href="#client-side-components-connections">Connections</a></li>
</ul>
</li>
<li>
<a href="#client-server-interactions">Client-Server Interactions</a>
<ul>
<li><a href="#streams">Streams</a></li>
<li><a href="#broadcasting">Broadcasting</a></li>
<li><a href="#client-server-interactions-subscriptions">Subscriptions</a></li>
<li><a href="#passing-parameters-to-channels">Passing Parameters to Channels</a></li>
<li><a href="#rebroadcasting-a-message">Rebroadcasting a Message</a></li>
</ul>
</li>
<li>
<a href="#full-stack-examples">Full-Stack Examples</a>
<ul>
<li><a href="#example-1-user-appearances">Example 1: User Appearances</a></li>
<li><a href="#example-2-receiving-new-web-notifications">Example 2: Receiving New Web Notifications</a></li>
<li><a href="#more-complete-examples">More Complete Examples</a></li>
</ul>
</li>
<li>
<a href="#configuration">Configuration</a>
<ul>
<li><a href="#subscription-adapter">Subscription Adapter</a></li>
<li><a href="#allowed-request-origins">Allowed Request Origins</a></li>
<li><a href="#consumer-configuration">Consumer Configuration</a></li>
<li><a href="#worker-pool-configuration">Worker Pool Configuration</a></li>
<li><a href="#other-configurations">Other Configurations</a></li>
</ul>
</li>
<li>
<a href="#running-standalone-cable-servers">Running Standalone Cable Servers</a>
<ul>
<li><a href="#in-app">In App</a></li>
<li><a href="#standalone">Standalone</a></li>
</ul>
</li>
<li><a href="#dependencies">Dependencies</a></li>
<li><a href="#deployment">Deployment</a></li>
<li><a href="#testing">Testing</a></li>
</ol>
</div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<h3 id="what-is-action-cable-questionmark"><a class="anchorlink" href="#what-is-action-cable-questionmark">1 What is Action Cable?</a></h3><p>Action Cable seamlessly integrates
<a href="https://en.wikipedia.org/wiki/WebSocket">WebSockets</a> con el resto de tu
Aplicación de Rails. Permite escribir características en tiempo real en Ruby en el
mismo estilo y forma que el resto de su aplicación Rails, sin dejar de ser
eficiente y escalable. Es una oferta de pila completa que proporciona tanto
marco JavaScript del lado del cliente y un marco Ruby del lado del servidor. Tienes
acceso a su modelo de dominio completo escrito con Active Record o su ORM de
elección.</p><h3 id="terminology"><a class="anchorlink" href="#terminology">2 Terminology</a></h3><p>Un solo servidor de Action Cable puede manejar múltiples instancias de conexión. Tiene uno
instancia de conexión por conexión WebSocket. Un solo usuario puede tener múltiples
WebSockets abiertos en su aplicación si utilizan varias pestañas o dispositivos del navegador.
El cliente de una conexión WebSocket se denomina consumidor.</p><p>Cada consumidor puede, a su vez, suscribirse a múltiples canales de cable. Cada canal
encapsula una unidad lógica de trabajo, similar a lo que hace un controlador en
una configuración regular de MVC. Por ejemplo, podría tener un <code>ChatChannel</code> y
un <code>AppearancesChannel</code>, y un consumidor podría suscribirse a
oa ambos canales. Como mínimo, un consumidor debe estar suscrito
a un canal.</p><p>When the consumer is subscribed to a channel, they act as a subscriber.
The connection between the subscriber and the channel is, surprise-surprise,
called a subscription. A consumer can act as a subscriber to a given channel
any number of times. For example, a consumer could subscribe to multiple chat rooms
at the same time. (And remember that a physical user may have multiple consumers,
one per tab/device open to your connection).</p><p>Cada canal puede volver a transmitir cero o más transmisiones.
Una radiodifusión es un enlace pubsub donde cualquier cosa transmitida por la emisora es
enviado directamente a los suscriptores del canal que están transmitiendo esa transmisión con nombre.</p><p>Como puede ver, esta es una pila arquitectónica bastante profunda. Hay muchas novedades
terminología para identificar las nuevas piezas, y además de eso, está tratando
con reflejos del lado del cliente y del servidor de cada unidad.</p><h3 id="what-is-pub-sub-questionmark"><a class="anchorlink" href="#what-is-pub-sub-questionmark">3 What is Pub/Sub?</a></h3><p><a href="https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern">Pub/Sub</a>, o
Publicar-Suscribir, se refiere a un paradigma de cola de mensajes mediante el cual los remitentes de
información (editores), envian datos a una clase abstracta de destinatarios
(suscriptores), sin especificar destinatarios individuales. Action Cable utiliza este
enfoque para comunicarse entre el servidor y muchos clientes.</p><h3 id="server-side-components"><a class="anchorlink" href="#server-side-components">4 Server-Side Components</a></h3><h4 id="server-side-components-connections"><a class="anchorlink" href="#server-side-components-connections">4.1 Connections</a></h4><p><em>Connections</em> forman la base de la relación cliente-servidor. Para cada
WebSocket aceptado por el servidor, se crea una instancia de un objeto de conexión. Este
objeto se convierte en el padre de todas las <em>channel subscriptions</em> que se crean
de ahí en adelante. La conexión en sí no se ocupa de ninguna aplicación específica
lógicamente más allá de la autenticación y autorización. El cliente de la conexión de
un WebSocket se llama conexión <em>consumer</em>. Un usuario individual creará
un par de conexión de consumidor por pestaña, ventana o dispositivo del navegador que tengan abierto.</p><p>Las conexiones son instancias de <code>ApplicationCable::Connection</code>. En esta clase, tu
autorizas la conexión entrante y procedes a establecerla si el usuario puede
ser identificado.</p><h5 id="connection-setup"><a class="anchorlink" href="#connection-setup">4.1.1 Connection Setup</a></h5><div class="code_container">
<pre><code class="highlight ruby"><span class="c1"># app/channels/application_cable/connection.rb</span>
<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="k">def</span> <span class="nf">connect</span>
<span class="nb">self</span><span class="p">.</span><span class="nf">current_user</span> <span class="o">=</span> <span class="n">find_verified_user</span>
<span class="k">end</span>
<span class="kp">private</span>
<span class="k">def</span> <span class="nf">find_verified_user</span>
<span class="k">if</span> <span class="n">verified_user</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">find_by</span><span class="p">(</span><span class="ss">id: </span><span class="n">cookies</span><span class="p">.</span><span class="nf">encrypted</span><span class="p">[</span><span class="ss">:user_id</span><span class="p">])</span>
<span class="n">verified_user</span>
<span class="k">else</span>
<span class="n">reject_unauthorized_connection</span>
<span class="k">end</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="# app/channels/application_cable/connection.rb
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = find_verified_user
end
private
def find_verified_user
if verified_user = User.find_by(id: cookies.encrypted[:user_id])
verified_user
else
reject_unauthorized_connection
end
end
end
end
">Copy</button>
</div>
<p>Aquí, <code>protected_by</code> es un identificador de conexión que se puede usar para encontrar la
conexión específica más tarde. Tenga en cuenta que todo lo que esté marcado como identificador
cree un delegado con el mismo nombre en cualquiera instancia de canal creada fuera de la conexión.</p><p>Este ejemplo se basa en el hecho de que ya habrá manejado la autenticación del usuario
en otro lugar de su aplicación, y que una autenticación exitosa establece un cifrado
cookie con el ID de usuario.</p><p>La cookie se envía automáticamente a la instancia de conexión cuando una nueva conexión
se intenta, y lo usa para establecer el <code>current_user</code>. Identificando la conexión
por este mismo usuario actual, también se asegura de que luego pueda recuperar todas las
conexiones de un usuario determinado (y potencialmente desconectarlas todas si el usuario es eliminado
o no autorizado).</p><p>Si su enfoque de autenticación incluye el uso de una sesión, utiliza el almacén de cookies para
la sesión, su cookie de sesión se llama <code>_session</code> y la clave de ID de usuario es<code>user_id</code> usted
puede utilizar este enfoque:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="n">verified_user</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">find_by</span><span class="p">(</span><span class="ss">id: </span><span class="n">cookies</span><span class="p">.</span><span class="nf">encrypted</span><span class="p">[</span><span class="s1">'_session'</span><span class="p">][</span><span class="s1">'user_id'</span><span class="p">])</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="verified_user = User.find_by(id: cookies.encrypted['_session']['user_id'])
">Copy</button>
</div>
<h5 id="connections-exception-handling"><a class="anchorlink" href="#connections-exception-handling">4.1.2 Exception Handling</a></h5><p>De forma predeterminada, las excepciones no controladas se capturan y registran en el registrador de Rails. Si a ti te gustaría
interceptar globalmente estas excepciones e informarlas a un servicio de seguimiento de errores externo, por
ejemplo, puede hacerlo con
<a href="https://edgeapi.rubyonrails.org/classes/ActiveSupport/Rescuable/ClassMethods.html#method-i-rescue_from"><code>rescue_from</code></a>.</p><div class="code_container">
<pre><code class="highlight ruby"><span class="c1"># app/channels/application_cable/connection.rb</span>
<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">rescue_from</span> <span class="no">StandardError</span><span class="p">,</span> <span class="ss">with: :report_error</span>
<span class="kp">private</span>
<span class="k">def</span> <span class="nf">report_error</span><span class="p">(</span><span class="n">e</span><span class="p">)</span>
<span class="no">SomeExternalBugtrackingService</span><span class="p">.</span><span class="nf">notify</span><span class="p">(</span><span class="n">e</span><span class="p">)</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="# app/channels/application_cable/connection.rb
module ApplicationCable
class Connection < ActionCable::Connection::Base
rescue_from StandardError, with: :report_error
private
def report_error(e)
SomeExternalBugtrackingService.notify(e)
end
end
end
">Copy</button>
</div>
<h4 id="channels"><a class="anchorlink" href="#channels">4.2 Channels</a></h4><p>Un <em>channel</em> encapsula una unidad lógica de trabajo, similar a lo que hace un controlador en un
configuración regular de MVC. Por defecto, Rails crea una clase principal <code>ApplicationCable::Channel</code>
para encapsular la lógica compartida entre sus canales.</p><h5 id="parent-channel-setup"><a class="anchorlink" href="#parent-channel-setup">4.2.1 Parent Channel Setup</a></h5><div class="code_container">
<pre><code class="highlight ruby"><span class="c1"># app/channels/application_cable/channel.rb</span>
<span class="k">module</span> <span class="nn">ApplicationCable</span>
<span class="k">class</span> <span class="nc">Channel</span> <span class="o"><</span> <span class="no">ActionCable</span><span class="o">::</span><span class="no">Channel</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="# app/channels/application_cable/channel.rb
module ApplicationCable
class Channel < ActionCable::Channel::Base
end
end
">Copy</button>
</div>
<p>Luego, crearía sus propias clases de canal. Por ejemplo, podría tener un
<code>ChatChannel</code> y un<code>AppearanceChannel</code>:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="c1"># app/channels/chat_channel.rb</span>
<span class="k">class</span> <span class="nc">ChatChannel</span> <span class="o"><</span> <span class="no">ApplicationCable</span><span class="o">::</span><span class="no">Channel</span>
<span class="k">end</span>
<span class="c1"># app/channels/appearance_channel.rb</span>
<span class="k">class</span> <span class="nc">AppearanceChannel</span> <span class="o"><</span> <span class="no">ApplicationCable</span><span class="o">::</span><span class="no">Channel</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="# app/channels/chat_channel.rb
class ChatChannel < ApplicationCable::Channel
end
# app/channels/appearance_channel.rb
class AppearanceChannel < ApplicationCable::Channel
end
">Copy</button>
</div>
<p>A continuación, un consumidor podría suscribirse a uno de estos canales oa ambos.</p><h5 id="channels-subscriptions"><a class="anchorlink" href="#channels-subscriptions">4.2.2 Subscriptions</a></h5><p>Los consumidores se suscriben a los canales, actuando como <em>subscribers</em>. Su conexión es
llamada <em>subscription</em>. Los mensajes producidos se enrutan luego a estos canales
suscripciones basadas en un identificador enviado por el consumidor de cable.</p><div class="code_container">
<pre><code class="highlight ruby"><span class="c1"># app/channels/chat_channel.rb</span>
<span class="k">class</span> <span class="nc">ChatChannel</span> <span class="o"><</span> <span class="no">ApplicationCable</span><span class="o">::</span><span class="no">Channel</span>
<span class="c1"># Called when the consumer has successfully</span>
<span class="c1"># become a subscriber to this channel.</span>
<span class="k">def</span> <span class="nf">subscribed</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="# app/channels/chat_channel.rb
class ChatChannel < ApplicationCable::Channel
# Called when the consumer has successfully
# become a subscriber to this channel.
def subscribed
end
end
">Copy</button>
</div>
<h5 id="channels-exception-handling"><a class="anchorlink" href="#channels-exception-handling">4.2.3 Exception Handling</a></h5><p>Al igual que con <code>ActionCable::Connection::Base</code>, también puedes usar <code>rescue_from</code> en un
canal específico para manejar excepciones planteadas:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="c1"># app/channels/chat_channel.rb</span>
<span class="k">class</span> <span class="nc">ChatChannel</span> <span class="o"><</span> <span class="no">ApplicationCable</span><span class="o">::</span><span class="no">Channel</span>
<span class="n">rescue_from</span> <span class="s1">'MyError'</span><span class="p">,</span> <span class="ss">with: :deliver_error_message</span>
<span class="kp">private</span>
<span class="k">def</span> <span class="nf">deliver_error_message</span><span class="p">(</span><span class="n">e</span><span class="p">)</span>
<span class="n">broadcast_to</span><span class="p">(</span><span class="o">...</span><span class="p">)</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="# app/channels/chat_channel.rb
class ChatChannel < ApplicationCable::Channel
rescue_from 'MyError', with: :deliver_error_message
private
def deliver_error_message(e)
broadcast_to(...)
end
end
">Copy</button>
</div>
<h3 id="client-side-components"><a class="anchorlink" href="#client-side-components">5 Client-Side Components</a></h3><h4 id="client-side-components-connections"><a class="anchorlink" href="#client-side-components-connections">5.1 Connections</a></h4><p>Los consumidores necesitan una instancia de la conexión de su lado. Esto puede ser
establecido usando el siguiente JavaScript, que es generado por defecto por Rails:</p><h5 id="connect-consumer"><a class="anchorlink" href="#connect-consumer">5.1.1 Connect Consumer</a></h5><div class="code_container">
<pre><code class="highlight js"><span class="c1">// app/javascript/channels/consumer.js</span>
<span class="c1">// Action Cable provides the framework to deal with WebSockets in Rails.</span>
<span class="c1">// You can generate new channels where WebSocket features live using the `bin/rails generate channel` command.</span>
<span class="k">import</span> <span class="p">{</span> <span class="nx">createConsumer</span> <span class="p">}</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">@rails/actioncable</span><span class="dl">"</span>
<span class="k">export</span> <span class="k">default</span> <span class="nx">createConsumer</span><span class="p">()</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text='// app/javascript/channels/consumer.js
// Action Cable provides the framework to deal with WebSockets in Rails.
// You can generate new channels where WebSocket features live using the `bin/rails generate channel` command.
import { createConsumer } from "@rails/actioncable"
export default createConsumer()
'>Copy</button>
</div>
<p>Esto preparará a un consumidor que se conectará contra <code>/cable</code> en su servidor de forma predeterminada.
La conexión no se establecerá hasta que también haya especificado al menos una suscripción
estás interesado en tener.</p><p>El consumidor puede, opcionalmente, tomar un argumento que especifique la URL a la que conectarse. Esta
puede ser una cadena, o una función que devuelve una cadena que se llamará cuando se abre el WebSocket.</p><div class="code_container">
<pre><code class="highlight js"><span class="c1">// Specify a different URL to connect to</span>
<span class="nx">createConsumer</span><span class="p">(</span><span class="dl">'</span><span class="s1">https://ws.example.com/cable</span><span class="dl">'</span><span class="p">)</span>
<span class="c1">// Use a function to dynamically generate the URL</span>
<span class="nx">createConsumer</span><span class="p">(</span><span class="nx">getWebSocketURL</span><span class="p">)</span>
<span class="kd">function</span> <span class="nx">getWebSocketURL</span> <span class="p">{</span>
<span class="kd">const</span> <span class="nx">token</span> <span class="o">=</span> <span class="nx">localStorage</span><span class="p">.</span><span class="kd">get</span><span class="p">(</span><span class="dl">'</span><span class="s1">auth-token</span><span class="dl">'</span><span class="p">)</span>
<span class="k">return</span> <span class="s2">`https://ws.example.com/cable?token=</span><span class="p">${</span><span class="nx">token</span><span class="p">}</span><span class="s2">`</span>
<span class="p">}</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="// Specify a different URL to connect to
createConsumer('https://ws.example.com/cable')
// Use a function to dynamically generate the URL
createConsumer(getWebSocketURL)
function getWebSocketURL {
const token = localStorage.get('auth-token')
return `https://ws.example.com/cable?token=${token}`
}
">Copy</button>
</div>
<h5 id="subscriber"><a class="anchorlink" href="#subscriber">5.1.2 Subscriber</a></h5><p>Un consumidor se convierte en suscriptor al crear una suscripción a un canal determinado:</p><div class="code_container">
<pre><code class="highlight js"><span class="c1">// app/javascript/channels/chat_channel.js</span>
<span class="k">import</span> <span class="nx">consumer</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">./consumer</span><span class="dl">"</span>
<span class="nx">consumer</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="s2">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="s2">Best Room</span><span class="dl">"</span> <span class="p">})</span>
<span class="c1">// app/javascript/channels/appearance_channel.js</span>
<span class="k">import</span> <span class="nx">consumer</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">./consumer</span><span class="dl">"</span>
<span class="nx">consumer</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="s2">AppearanceChannel</span><span class="dl">"</span> <span class="p">})</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text='// app/javascript/channels/chat_channel.js
import consumer from "./consumer"
consumer.subscriptions.create({ channel: "ChatChannel", room: "Best Room" })
// app/javascript/channels/appearance_channel.js
import consumer from "./consumer"
consumer.subscriptions.create({ channel: "AppearanceChannel" })
'>Copy</button>
</div>
<p>Si bien esto crea la suscripción, la funcionalidad necesaria para responder a
los datos recibidos se describirán más adelante.</p><p>Un consumidor puede actuar como suscriptor de un canal determinado tantas veces como desee.
Por ejemplo, un consumidor podría suscribirse a varias salas de chat al mismo tiempo:</p><div class="code_container">
<pre><code class="highlight js"><span class="c1">// app/javascript/channels/chat_channel.js</span>
<span class="k">import</span> <span class="nx">consumer</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">./consumer</span><span class="dl">"</span>
<span class="nx">consumer</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="s2">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="s2">1st Room</span><span class="dl">"</span> <span class="p">})</span>
<span class="nx">consumer</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="s2">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="s2">2nd Room</span><span class="dl">"</span> <span class="p">})</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text='// app/javascript/channels/chat_channel.js
import consumer from "./consumer"
consumer.subscriptions.create({ channel: "ChatChannel", room: "1st Room" })
consumer.subscriptions.create({ channel: "ChatChannel", room: "2nd Room" })
'>Copy</button>
</div>
<h3 id="client-server-interactions"><a class="anchorlink" href="#client-server-interactions">6 Client-Server Interactions</a></h3><h4 id="streams"><a class="anchorlink" href="#streams">6.1 Streams</a></h4><p><em>Streams</em> proporcionan el mecanismo por el cual los canales enrutan el contenido publicado
(transmisiones) a sus suscriptores. El siguiente ejemplo
suscríbase a la transmisión <code>chat_Best Room</code> si el parámetro de la sala
es <code>Best Room</code>:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="c1"># app/channels/chat_channel.rb</span>
<span class="k">class</span> <span class="nc">ChatChannel</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="s2">"chat_</span><span class="si">#{</span><span class="n">params</span><span class="p">[</span><span class="ss">:room</span><span class="p">]</span><span class="si">}</span><span class="s2">"</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text='# app/channels/chat_channel.rb
class ChatChannel < ApplicationCable::Channel
def subscribed
stream_from "chat_#{params[:room]}"
end
end
'>Copy</button>
</div>
<p>Si tiene una transmisión relacionada con un modelo, la transmisión utilizada
se puede generar a partir del canal y el modelo. El siguiente ejemplo
suscríbete a una transmisión como <code>comments:Z2lkOi8vVGVzdEFwcC9Qb3N0LzE</code>,
donde <code>Z2lkOi8vVGVzdEFwcC9Qb3N0LzE</code> es el GlobalID del modelo de publicación.</p><div class="code_container">
<pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">CommentsChannel</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">post</span> <span class="o">=</span> <span class="no">Post</span><span class="p">.</span><span class="nf">find</span><span class="p">(</span><span class="n">params</span><span class="p">[</span><span class="ss">:id</span><span class="p">])</span>
<span class="n">stream_for</span> <span class="n">post</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="class CommentsChannel < ApplicationCable::Channel
def subscribed
post = Post.find(params[:id])
stream_for post
end
end
">Copy</button>
</div>
<p>Luego puede transmitir a este canal de esta manera:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="no">CommentsChannel</span><span class="p">.</span><span class="nf">broadcast_to</span><span class="p">(</span><span class="vi">@post</span><span class="p">,</span> <span class="vi">@comment</span><span class="p">)</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="CommentsChannel.broadcast_to(@post, @comment)
">Copy</button>
</div>
<h4 id="broadcasting"><a class="anchorlink" href="#broadcasting">6.2 Broadcasting</a></h4><p>Un <em>broadcasting</em> es un enlace pub/sub donde cualquier cosa transmitida por un editor
se enruta directamente a los suscriptores del canal que están transmitiendo ese nombre
radiodifusión. Cada canal puede transmitir cero o más transmisiones.</p><p>Las transmisiones son puramente una cola en línea y dependen del tiempo. Si un consumidor
no esta transmitiendo (suscrito a un canal determinado), no recibirán la transmisión
si se conectan más tarde.</p><p>Las transmisiones se llaman en otra parte de su aplicación Rails:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="no">WebNotificationsChannel</span><span class="p">.</span><span class="nf">broadcast_to</span><span class="p">(</span>
<span class="n">current_user</span><span class="p">,</span>
<span class="ss">title: </span><span class="s1">'New things!'</span><span class="p">,</span>
<span class="ss">body: </span><span class="s1">'All the news fit to print'</span>
<span class="p">)</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="WebNotificationsChannel.broadcast_to(
current_user,
title: 'New things!',
body: 'All the news fit to print'
)
">Copy</button>
</div>
<p>La llamada <code>WebNotificationsChannel.broadcast_to</code> coloca un mensaje en el
la cola pubsub del adaptador de suscripción con un nombre de transmisión independiente para cada usuario.
La cola de pubsub predeterminada para Action Cable es <code>redis</code> en producción y <code>async</code> en desarrollo y
entornos de prueba. Para un usuario con un ID de 1, el nombre de la transmisión sería <code>web_notifications:1</code>.</p><p>El canal ha recibido instrucciones para transmitir todo lo que llega a
<code>web_notifications:1</code> directamente al cliente invocando el <code>recibido</code>
llamar de vuelta.</p><h4 id="client-server-interactions-subscriptions"><a class="anchorlink" href="#client-server-interactions-subscriptions">6.3 Subscriptions</a></h4><p>Cuando un consumidor está suscrito a un canal, actúa como suscriptor. Esta
conexión se llama suscripción. Los mensajes entrantes luego se enrutan a
estas suscripciones de canal que se basan en un identificador enviado por el consumidor de cable.</p><div class="code_container">
<pre><code class="highlight js"><span class="c1">// app/javascript/channels/chat_channel.js</span>
<span class="c1">// Assumes you've already requested the right to send web notifications</span>
<span class="k">import</span> <span class="nx">consumer</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">./consumer</span><span class="dl">"</span>
<span class="nx">consumer</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="s2">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="s2">Best Room</span><span class="dl">"</span> <span class="p">},</span> <span class="p">{</span>
<span class="nx">received</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span> <span class="p">{</span>
<span class="k">this</span><span class="p">.</span><span class="nx">appendLine</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span>
<span class="p">},</span>
<span class="nx">appendLine</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span> <span class="p">{</span>
<span class="kd">const</span> <span class="nx">html</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">createLine</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span>
<span class="kd">const</span> <span class="nx">element</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">querySelector</span><span class="p">(</span><span class="dl">"</span><span class="s2">[data-chat-room='Best Room']</span><span class="dl">"</span><span class="p">)</span>
<span class="nx">element</span><span class="p">.</span><span class="nx">insertAdjacentHTML</span><span class="p">(</span><span class="dl">"</span><span class="s2">beforeend</span><span class="dl">"</span><span class="p">,</span> <span class="nx">html</span><span class="p">)</span>
<span class="p">},</span>
<span class="nx">createLine</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span> <span class="p">{</span>
<span class="k">return</span> <span class="s2">`
<article class="chat-line">
<span class="speaker"></span><span class="p">${</span><span class="nx">data</span><span class="p">[</span><span class="dl">"</span><span class="s2">sent_by</span><span class="dl">"</span><span class="p">]}</span><span class="s2"></span>
<span class="body"></span><span class="p">${</span><span class="nx">data</span><span class="p">[</span><span class="dl">"</span><span class="s2">body</span><span class="dl">"</span><span class="p">]}</span><span class="s2"></span>
</article>
`</span>
<span class="p">}</span>
<span class="p">})</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="// app/javascript/channels/chat_channel.js
// Assumes you've already requested the right to send web notifications
import consumer from "./consumer"
consumer.subscriptions.create({ channel: "ChatChannel", room: "Best Room" }, {
received(data) {
this.appendLine(data)
},
appendLine(data) {
const html = this.createLine(data)
const element = document.querySelector("[data-chat-room='Best Room']")
element.insertAdjacentHTML("beforeend", html)
},
createLine(data) {
return `
<article class="chat-line">
<span class="speaker">${data["sent_by"]}</span>
<span class="body">${data["body"]}</span>
</article>
`
}
})
">Copy</button>
</div>
<h4 id="passing-parameters-to-channels"><a class="anchorlink" href="#passing-parameters-to-channels">6.4 Passing Parameters to Channels</a></h4><p>Puede pasar parámetros del lado del cliente al lado del servidor al crear un
suscripción. Por ejemplo:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="c1"># app/channels/chat_channel.rb</span>
<span class="k">class</span> <span class="nc">ChatChannel</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="s2">"chat_</span><span class="si">#{</span><span class="n">params</span><span class="p">[</span><span class="ss">:room</span><span class="p">]</span><span class="si">}</span><span class="s2">"</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text='# app/channels/chat_channel.rb
class ChatChannel < ApplicationCable::Channel
def subscribed
stream_from "chat_#{params[:room]}"
end
end
'>Copy</button>
</div>
<p>Un objeto pasado como primer argumento a <code>subscriptions.create</code> se convierte en el
hash de params en el canal de cable. Se requiere la palabra clave <code>canal</code>:</p><div class="code_container">
<pre><code class="highlight js"><span class="c1">// app/javascript/channels/chat_channel.js</span>
<span class="k">import</span> <span class="nx">consumer</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">./consumer</span><span class="dl">"</span>
<span class="nx">consumer</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="s2">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="s2">Best Room</span><span class="dl">"</span> <span class="p">},</span> <span class="p">{</span>
<span class="nx">received</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span> <span class="p">{</span>
<span class="k">this</span><span class="p">.</span><span class="nx">appendLine</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span>
<span class="p">},</span>
<span class="nx">appendLine</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span> <span class="p">{</span>
<span class="kd">const</span> <span class="nx">html</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">createLine</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span>
<span class="kd">const</span> <span class="nx">element</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">querySelector</span><span class="p">(</span><span class="dl">"</span><span class="s2">[data-chat-room='Best Room']</span><span class="dl">"</span><span class="p">)</span>
<span class="nx">element</span><span class="p">.</span><span class="nx">insertAdjacentHTML</span><span class="p">(</span><span class="dl">"</span><span class="s2">beforeend</span><span class="dl">"</span><span class="p">,</span> <span class="nx">html</span><span class="p">)</span>
<span class="p">},</span>
<span class="nx">createLine</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span> <span class="p">{</span>
<span class="k">return</span> <span class="s2">`
<article class="chat-line">
<span class="speaker"></span><span class="p">${</span><span class="nx">data</span><span class="p">[</span><span class="dl">"</span><span class="s2">sent_by</span><span class="dl">"</span><span class="p">]}</span><span class="s2"></span>
<span class="body"></span><span class="p">${</span><span class="nx">data</span><span class="p">[</span><span class="dl">"</span><span class="s2">body</span><span class="dl">"</span><span class="p">]}</span><span class="s2"></span>
</article>
`</span>
<span class="p">}</span>
<span class="p">})</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="// app/javascript/channels/chat_channel.js
import consumer from "./consumer"
consumer.subscriptions.create({ channel: "ChatChannel", room: "Best Room" }, {
received(data) {
this.appendLine(data)
},
appendLine(data) {
const html = this.createLine(data)
const element = document.querySelector("[data-chat-room='Best Room']")
element.insertAdjacentHTML("beforeend", html)
},
createLine(data) {
return `
<article class="chat-line">
<span class="speaker">${data["sent_by"]}</span>
<span class="body">${data["body"]}</span>
</article>
`
}
})
">Copy</button>
</div>
<div class="code_container">
<pre><code class="highlight ruby"><span class="c1"># Somewhere in your app this is called, perhaps</span>
<span class="c1"># from a NewCommentJob.</span>
<span class="no">ActionCable</span><span class="p">.</span><span class="nf">server</span><span class="p">.</span><span class="nf">broadcast</span><span class="p">(</span>
<span class="s2">"chat_</span><span class="si">#{</span><span class="n">room</span><span class="si">}</span><span class="s2">"</span><span class="p">,</span>
<span class="ss">sent_by: </span><span class="s1">'Paul'</span><span class="p">,</span>
<span class="ss">body: </span><span class="s1">'This is a cool chat app.'</span>
<span class="p">)</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="# Somewhere in your app this is called, perhaps
# from a NewCommentJob.
ActionCable.server.broadcast(
"chat_#{room}",
sent_by: 'Paul',
body: 'This is a cool chat app.'
)
">Copy</button>
</div>
<h4 id="rebroadcasting-a-message"><a class="anchorlink" href="#rebroadcasting-a-message">6.5 Rebroadcasting a Message</a></h4><p>Un caso de uso común es <em>rebroadcast</em> un mensaje enviado por un cliente a cualquier
otros clientes conectados.</p><div class="code_container">
<pre><code class="highlight ruby"><span class="c1"># app/channels/chat_channel.rb</span>
<span class="k">class</span> <span class="nc">ChatChannel</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="s2">"chat_</span><span class="si">#{</span><span class="n">params</span><span class="p">[</span><span class="ss">:room</span><span class="p">]</span><span class="si">}</span><span class="s2">"</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">receive</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
<span class="no">ActionCable</span><span class="p">.</span><span class="nf">server</span><span class="p">.</span><span class="nf">broadcast</span><span class="p">(</span><span class="s2">"chat_</span><span class="si">#{</span><span class="n">params</span><span class="p">[</span><span class="ss">:room</span><span class="p">]</span><span class="si">}</span><span class="s2">"</span><span class="p">,</span> <span class="n">data</span><span class="p">)</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text='# app/channels/chat_channel.rb
class ChatChannel < ApplicationCable::Channel
def subscribed
stream_from "chat_#{params[:room]}"
end
def receive(data)
ActionCable.server.broadcast("chat_#{params[:room]}", data)
end
end
'>Copy</button>
</div>
<div class="code_container">
<pre><code class="highlight js"><span class="c1">// app/javascript/channels/chat_channel.js</span>
<span class="k">import</span> <span class="nx">consumer</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">./consumer</span><span class="dl">"</span>
<span class="kd">const</span> <span class="nx">chatChannel</span> <span class="o">=</span> <span class="nx">consumer</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="s2">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="s2">Best Room</span><span class="dl">"</span> <span class="p">},</span> <span class="p">{</span>
<span class="nx">received</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span> <span class="p">{</span>
<span class="c1">// data => { sent_by: "Paul", body: "This is a cool chat app." }</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="nx">chatChannel</span><span class="p">.</span><span class="nx">send</span><span class="p">({</span> <span class="na">sent_by</span><span class="p">:</span> <span class="dl">"</span><span class="s2">Paul</span><span class="dl">"</span><span class="p">,</span> <span class="na">body</span><span class="p">:</span> <span class="dl">"</span><span class="s2">This is a cool chat app.</span><span class="dl">"</span> <span class="p">})</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text='// app/javascript/channels/chat_channel.js
import consumer from "./consumer"
const chatChannel = consumer.subscriptions.create({ channel: "ChatChannel", room: "Best Room" }, {
received(data) {
// data => { sent_by: "Paul", body: "This is a cool chat app." }
}
}
chatChannel.send({ sent_by: "Paul", body: "This is a cool chat app." })
'>Copy</button>
</div>
<p>La retransmisión será recibida por todos los clientes conectados, <em>incluyendo</em> el
cliente que envió el mensaje. Tenga en cuenta que los parámetros son los mismos que cuando
te suscribiste al canal.</p><h3 id="full-stack-examples"><a class="anchorlink" href="#full-stack-examples">7 Full-Stack Examples</a></h3><p>Los siguientes pasos de configuración son comunes a ambos ejemplos:</p>
<ol>
<li>
<a href="#connection-setup">Setup your connection</a>.</li>
<li>
<a href="#parent-channel-setup">Setup your parent channel</a>.</li>
<li>
<a href="#connect-consumer">Connect your consumer</a>.</li>
</ol>
<h4 id="example-1-user-appearances"><a class="anchorlink" href="#example-1-user-appearances">7.1 Example 1: User Appearances</a></h4><p>Aquí hay un ejemplo simple de un canal que rastrea si un usuario está en línea o no
y en qué página están. (Esto es útil para crear funciones de presencia como mostrar
un punto verde junto a un nombre de usuario si está en línea).</p><p>Cree el canal de apariencia del lado del servidor:</p><div class="code_container">
<pre><code class="highlight ruby"><span class="c1"># app/channels/appearance_channel.rb</span>
<span class="k">class</span> <span class="nc">AppearanceChannel</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">current_user</span><span class="p">.</span><span class="nf">appear</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">unsubscribed</span>
<span class="n">current_user</span><span class="p">.</span><span class="nf">disappear</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">appear</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
<span class="n">current_user</span><span class="p">.</span><span class="nf">appear</span><span class="p">(</span><span class="ss">on: </span><span class="n">data</span><span class="p">[</span><span class="s1">'appearing_on'</span><span class="p">])</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">away</span>
<span class="n">current_user</span><span class="p">.</span><span class="nf">away</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="# app/channels/appearance_channel.rb
class AppearanceChannel < ApplicationCable::Channel
def subscribed
current_user.appear
end
def unsubscribed
current_user.disappear
end
def appear(data)
current_user.appear(on: data['appearing_on'])
end
def away
current_user.away
end
end
">Copy</button>
</div>
<p>Cuando se inicia una suscripción, la devolución de llamada <code>subscribed</code> se activa y uno
aprovecha la oportunidad para decir "el usuario actual ha aparecido". Ese
API de aparecer/desaparecer podría estar respaldado por Redis, una base de datos o cualquier otra cosa.</p><p>Cree la suscripción del canal de apariencia del lado del cliente:</p><div class="code_container">
<pre><code class="highlight js"><span class="c1">// app/javascript/channels/appearance_channel.js</span>
<span class="k">import</span> <span class="nx">consumer</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">./consumer</span><span class="dl">"</span>
<span class="nx">consumer</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="dl">"</span><span class="s2">AppearanceChannel</span><span class="dl">"</span><span class="p">,</span> <span class="p">{</span>
<span class="c1">// Called once when the subscription is created.</span>
<span class="nx">initialized</span><span class="p">()</span> <span class="p">{</span>
<span class="k">this</span><span class="p">.</span><span class="nx">update</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">update</span><span class="p">.</span><span class="nx">bind</span><span class="p">(</span><span class="k">this</span><span class="p">)</span>
<span class="p">},</span>
<span class="c1">// Called when the subscription is ready for use on the server.</span>
<span class="nx">connected</span><span class="p">()</span> <span class="p">{</span>
<span class="k">this</span><span class="p">.</span><span class="nx">install</span><span class="p">()</span>
<span class="k">this</span><span class="p">.</span><span class="nx">update</span><span class="p">()</span>
<span class="p">},</span>
<span class="c1">// Called when the WebSocket connection is closed.</span>
<span class="nx">disconnected</span><span class="p">()</span> <span class="p">{</span>
<span class="k">this</span><span class="p">.</span><span class="nx">uninstall</span><span class="p">()</span>
<span class="p">},</span>
<span class="c1">// Called when the subscription is rejected by the server.</span>
<span class="nx">rejected</span><span class="p">()</span> <span class="p">{</span>
<span class="k">this</span><span class="p">.</span><span class="nx">uninstall</span><span class="p">()</span>
<span class="p">},</span>
<span class="nx">update</span><span class="p">()</span> <span class="p">{</span>
<span class="k">this</span><span class="p">.</span><span class="nx">documentIsActive</span> <span class="p">?</span> <span class="k">this</span><span class="p">.</span><span class="nx">appear</span><span class="p">()</span> <span class="p">:</span> <span class="k">this</span><span class="p">.</span><span class="nx">away</span><span class="p">()</span>
<span class="p">},</span>
<span class="nx">appear</span><span class="p">()</span> <span class="p">{</span>
<span class="c1">// Calls `AppearanceChannel#appear(data)` on the server.</span>
<span class="k">this</span><span class="p">.</span><span class="nx">perform</span><span class="p">(</span><span class="dl">"</span><span class="s2">appear</span><span class="dl">"</span><span class="p">,</span> <span class="p">{</span> <span class="na">appearing_on</span><span class="p">:</span> <span class="k">this</span><span class="p">.</span><span class="nx">appearingOn</span> <span class="p">})</span>
<span class="p">},</span>
<span class="nx">away</span><span class="p">()</span> <span class="p">{</span>
<span class="c1">// Calls `AppearanceChannel#away` on the server.</span>
<span class="k">this</span><span class="p">.</span><span class="nx">perform</span><span class="p">(</span><span class="dl">"</span><span class="s2">away</span><span class="dl">"</span><span class="p">)</span>
<span class="p">},</span>
<span class="nx">install</span><span class="p">()</span> <span class="p">{</span>
<span class="nb">window</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="dl">"</span><span class="s2">focus</span><span class="dl">"</span><span class="p">,</span> <span class="k">this</span><span class="p">.</span><span class="nx">update</span><span class="p">)</span>
<span class="nb">window</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="dl">"</span><span class="s2">blur</span><span class="dl">"</span><span class="p">,</span> <span class="k">this</span><span class="p">.</span><span class="nx">update</span><span class="p">)</span>
<span class="nb">document</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="dl">"</span><span class="s2">turbolinks:load</span><span class="dl">"</span><span class="p">,</span> <span class="k">this</span><span class="p">.</span><span class="nx">update</span><span class="p">)</span>
<span class="nb">document</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="dl">"</span><span class="s2">visibilitychange</span><span class="dl">"</span><span class="p">,</span> <span class="k">this</span><span class="p">.</span><span class="nx">update</span><span class="p">)</span>
<span class="p">},</span>
<span class="nx">uninstall</span><span class="p">()</span> <span class="p">{</span>
<span class="nb">window</span><span class="p">.</span><span class="nx">removeEventListener</span><span class="p">(</span><span class="dl">"</span><span class="s2">focus</span><span class="dl">"</span><span class="p">,</span> <span class="k">this</span><span class="p">.</span><span class="nx">update</span><span class="p">)</span>
<span class="nb">window</span><span class="p">.</span><span class="nx">removeEventListener</span><span class="p">(</span><span class="dl">"</span><span class="s2">blur</span><span class="dl">"</span><span class="p">,</span> <span class="k">this</span><span class="p">.</span><span class="nx">update</span><span class="p">)</span>
<span class="nb">document</span><span class="p">.</span><span class="nx">removeEventListener</span><span class="p">(</span><span class="dl">"</span><span class="s2">turbolinks:load</span><span class="dl">"</span><span class="p">,</span> <span class="k">this</span><span class="p">.</span><span class="nx">update</span><span class="p">)</span>
<span class="nb">document</span><span class="p">.</span><span class="nx">removeEventListener</span><span class="p">(</span><span class="dl">"</span><span class="s2">visibilitychange</span><span class="dl">"</span><span class="p">,</span> <span class="k">this</span><span class="p">.</span><span class="nx">update</span><span class="p">)</span>
<span class="p">},</span>
<span class="kd">get</span> <span class="nx">documentIsActive</span><span class="p">()</span> <span class="p">{</span>
<span class="k">return</span> <span class="nb">document</span><span class="p">.</span><span class="nx">visibilityState</span> <span class="o">==</span> <span class="dl">"</span><span class="s2">visible</span><span class="dl">"</span> <span class="o">&&</span> <span class="nb">document</span><span class="p">.</span><span class="nx">hasFocus</span><span class="p">()</span>
<span class="p">},</span>
<span class="kd">get</span> <span class="nx">appearingOn</span><span class="p">()</span> <span class="p">{</span>
<span class="kd">const</span> <span class="nx">element</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">querySelector</span><span class="p">(</span><span class="dl">"</span><span class="s2">[data-appearing-on]</span><span class="dl">"</span><span class="p">)</span>
<span class="k">return</span> <span class="nx">element</span> <span class="p">?</span> <span class="nx">element</span><span class="p">.</span><span class="nx">getAttribute</span><span class="p">(</span><span class="dl">"</span><span class="s2">data-appearing-on</span><span class="dl">"</span><span class="p">)</span> <span class="p">:</span> <span class="kc">null</span>
<span class="p">}</span>
<span class="p">})</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text='// app/javascript/channels/appearance_channel.js
import consumer from "./consumer"
consumer.subscriptions.create("AppearanceChannel", {
// Called once when the subscription is created.
initialized() {
this.update = this.update.bind(this)
},
// Called when the subscription is ready for use on the server.
connected() {
this.install()
this.update()
},
// Called when the WebSocket connection is closed.
disconnected() {
this.uninstall()
},
// Called when the subscription is rejected by the server.
rejected() {
this.uninstall()
},
update() {
this.documentIsActive ? this.appear() : this.away()
},
appear() {
// Calls `AppearanceChannel#appear(data)` on the server.
this.perform("appear", { appearing_on: this.appearingOn })
},
away() {
// Calls `AppearanceChannel#away` on the server.
this.perform("away")
},
install() {
window.addEventListener("focus", this.update)
window.addEventListener("blur", this.update)
document.addEventListener("turbolinks:load", this.update)
document.addEventListener("visibilitychange", this.update)
},
uninstall() {
window.removeEventListener("focus", this.update)
window.removeEventListener("blur", this.update)
document.removeEventListener("turbolinks:load", this.update)
document.removeEventListener("visibilitychange", this.update)
},
get documentIsActive() {
return document.visibilityState == "visible" && document.hasFocus()
},
get appearingOn() {
const element = document.querySelector("[data-appearing-on]")
return element ? element.getAttribute("data-appearing-on") : null
}
})
'>Copy</button>
</div>
<h6 id="client-server-interaction"><a class="anchorlink" href="#client-server-interaction">7.1.1 Client-Server Interaction</a></h6>
<ol>
<li><p><strong>Client</strong> se conecta al <strong>Server</strong> vía <code>App.cable =
ActionCable.createConsumer("ws://cable.example.com")</code>. (<code>cable.js</code>). El
<strong>Server</strong> identifica esta conexión por <code>current_user</code>.</p></li>
<li><p><strong>Client</strong> se suscribe al canal de aparición a través de
<code>consumer.subscriptions.create({ channel: "AppearanceChannel" })</code>. (<code>appearance_channel.js</code>)</p></li>
<li><p><strong>Server</strong> reconoce que se ha iniciado una nueva suscripción para el
canal de apariencia y ejecuta su callback <code>subscribed</code>, llamando al
método <code>appear</code> en <code>current_user</code>. (<code>appearance_channel.rb</code>)</p></li>
<li><p><strong>Client</strong> reconoce que se ha establecido una suscripción y llama
<code>connected</code> (<code>appearance_channel.js</code>) que a su vez llama <code>install</code> y <code>appear</code>.
<code>appear</code> llama <code>AppearanceChannel#appear(data)</code> en el servidor y proporciona un
hash de datos de <code>{ appearing_on: this.appearingOn }</code>. Esto es
posible porque la instancia del canal del lado del servidor expone automáticamente todos
métodos públicos declarados en la clase (menos las devoluciones de llamada), para que estos puedan ser
alcanzado como llamadas de procedimiento remoto a través del método <code>perform</code> de una suscripción.</p></li>
<li><p><strong>Server</strong> recibe la solicitud de <code>appear</code> acción sobre la apariencia
canal para la conexión identificada por <code>current_user</code>
(<code>appearance_channel.rb</code>). <strong>Server</strong> recupera los datos con el
<code>:appearing_on</code> clave del hash de datos y lo establece como el valor para la clave <code>:on</code>
que se pasa a <code>current_user.appear</code>.</p></li>
</ol>
<h4 id="example-2-receiving-new-web-notifications"><a class="anchorlink" href="#example-2-receiving-new-web-notifications">7.2 Example 2: Receiving New Web Notifications</a></h4><p>El ejemplo de apariencia tenía que ver con exponer la funcionalidad del servidor a
invocación del lado del cliente a través de la conexión WebSocket. Pero la gran cosa
sobre WebSockets es que es una calle de doble sentido. Así que ahora mostremos un ejemplo
donde el servidor invoca una acción en el cliente.</p><p>Este es un canal de notificación web que le permite activar el lado del cliente
notificaciones web cuando transmite a las transmisiones correctas:</p><p>Cree el canal de notificaciones web del lado del servidor:</p><div class="code_container">