-
Notifications
You must be signed in to change notification settings - Fork 0
/
initialization.html
1179 lines (1078 loc) · 80.4 KB
/
initialization.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 dir="ltr" lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>El Proceso de Inicialización de Rails — Ruby on Rails Guides</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style-v2.css" data-turbo-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/print-v2.css" media="print">
<link rel="stylesheet" type="text/css" href="stylesheets/highlight-v2.css" data-turbo-track="reload">
<link rel="icon" href="images/favicon.ico" sizes="any">
<link rel="apple-touch-icon" href="images/icon.png">
<script src="javascripts/@hotwired--turbo.js" data-turbo-track="reload"></script>
<script src="javascripts/clipboard.js" data-turbo-track="reload"></script>
<script src="javascripts/guides.js" data-turbo-track="reload"></script>
<meta property="og:title" content="El Proceso de Inicialización de Rails — Ruby on Rails Guides" />
<meta name="description" content="NO LEA ESTE ARCHIVO EN GITHUB, LAS GUÍAS ESTÁN PUBLICADAS EN https://guides.rubyonrails.org.El Proceso de Inicialización de RailsEsta guía explica los aspectos internos del proceso de inicialización en Rails. Es una guía extremadamente detallada y se recomienda para desarrolladores avanzados de Rails.Después de leer esta guía, sabrás: Cómo usar bin/rails server. La secuencia temporal de la inicialización de Rails. Dónde se requieren diferentes archivos en la secuencia de arranque. Cómo se define y se utiliza la interfaz de Rails::Server." />
<meta property="og:description" content="NO LEA ESTE ARCHIVO EN GITHUB, LAS GUÍAS ESTÁN PUBLICADAS EN https://guides.rubyonrails.org.El Proceso de Inicialización de RailsEsta guía explica los aspectos internos del proceso de inicialización en Rails. Es una guía extremadamente detallada y se recomienda para desarrolladores avanzados de Rails.Después de leer esta guía, sabrás: Cómo usar bin/rails server. La secuencia temporal de la inicialización de Rails. Dónde se requieren diferentes archivos en la secuencia de arranque. Cómo se define y se utiliza la interfaz de Rails::Server." />
<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" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Arabic:[email protected]&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Heebo:[email protected]&family=Noto+Sans+Arabic:[email protected]&display=swap" rel="stylesheet">
<meta name="theme-color" content="#C81418">
</head>
<body class="guide">
<nav id="topNav" aria-label="Secondary">
<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://rubyonrails.org/blog">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://discuss.rubyonrails.org/">Foro</a></li>
<li class="more-info"><a href="https://github.com/rails/rails">Contribuir en GitHub</a></li>
</ul>
</div>
</nav>
<header id="page_header">
<div class="wrapper clearfix">
<nav id="feature_nav">
<div class="header-logo">
<a href="index.html" title="Regresar a la página principal de Guías para Edge">Guías</a>
<span id="version_switcher">
Versión:
<select class="guides-version">
<option value="https://edgeguides.rubyonrails.org/" selected>Edge</option>
<option value="https://guides.rubyonrails.org/v7.2/">7.2</option>
<option value="https://guides.rubyonrails.org/v7.1/">7.1</option>
<option value="https://guides.rubyonrails.org/v7.0/">7.0</option>
<option value="https://guides.rubyonrails.org/v6.1/">6.1</option>
<option value="https://guides.rubyonrails.org/v6.0/">6.0</option>
<option value="https://guides.rubyonrails.org/v5.2/">5.2</option>
<option value="https://guides.rubyonrails.org/v5.1/">5.1</option>
<option value="https://guides.rubyonrails.org/v5.0/">5.0</option>
<option value="https://guides.rubyonrails.org/v4.2/">4.2</option>
<option value="https://guides.rubyonrails.org/v4.1/">4.1</option>
<option value="https://guides.rubyonrails.org/v4.0/">4.0</option>
<option value="https://guides.rubyonrails.org/v3.2/">3.2</option>
<option value="https://guides.rubyonrails.org/v3.1/">3.1</option>
<option value="https://guides.rubyonrails.org/v3.0/">3.0</option>
<option value="https://guides.rubyonrails.org/v2.3/">2.3</option>
</select>
</span>
</div>
<ul class="nav">
<li><a class="nav-item" id="home_nav" href="https://rubyonrails.org/">Inicio</a></li>
<li class="guides-index guides-index-large">
<a href="index.html" id="guidesMenu" class="guides-index-item nav-item">Índice de Guías</a>
<div id="guides" class="clearfix" style="display: none;">
<hr />
<dl class="guides-section-container">
<div class="guides-section">
<dt>Comienza Aquí</dt>
<dd><a href="getting_started.html">Primeros Pasos con 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>
</div>
<div class="guides-section">
<dt>Vistas</dt>
<dd><a href="action_view_overview.html">Resumen de Action View</a></dd>
<dd><a href="layouts_and_rendering.html">Diseños y Renderizado en Rails</a></dd>
</div>
<div class="guides-section">
<dt>Controladores</dt>
<dd><a href="action_controller_overview.html">Resumen de Action Controller</a></dd>
<dd><a href="routing.html">Enrutamiento en Rails desde el Exterior</a></dd>
</div>
<div class="guides-section">
<dt>Otros Componentes</dt>
<dd><a href="active_support_core_extensions.html">Extensiones Básicas de Active Support</a></dd>
<dd><a href="action_mailer_basics.html">Conceptos Básicos de Action Mailer</a></dd>
<dd><a href="action_mailbox_basics.html">Conceptos Básicos de Action Mailbox</a></dd>
<dd><a href="action_text_overview.html">Resumen de Action Text</a></dd>
<dd><a href="active_job_basics.html">Conceptos Básicos de Active Job</a></dd>
</div>
<div class="guides-section">
<dt>Políticas</dt>
<dd><a href="maintenance_policy.html">Política de Mantenimiento</a></dd>
</div>
<div class="guides-section">
<dt>Notas de Lanzamiento</dt>
<dd><a href="upgrading_ruby_on_rails.html">Actualizando Ruby on Rails</a></dd>
<dd><a href="7_2_release_notes.html">Versión 7.2 - ?</a></dd>
<dd><a href="7_1_release_notes.html">Versión 7.1 - Octubre 2023</a></dd>
<dd><a href="7_0_release_notes.html">Versión 7.0 - Diciembre 2021</a></dd>
<dd><a href="6_1_release_notes.html">Versión 6.1 - Diciembre 2020</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">Índice de Guías</option>
<optgroup label="Comienza Aquí">
<option value="getting_started.html">Primeros Pasos con 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>
</optgroup>
<optgroup label="Vistas">
<option value="action_view_overview.html">Resumen de Action View</option>
<option value="layouts_and_rendering.html">Diseños y Renderizado en Rails</option>
</optgroup>
<optgroup label="Controladores">
<option value="action_controller_overview.html">Resumen de Action Controller</option>
<option value="routing.html">Enrutamiento en Rails desde el Exterior</option>
</optgroup>
<optgroup label="Otros Componentes">
<option value="active_support_core_extensions.html">Extensiones Básicas de Active Support</option>
<option value="action_mailer_basics.html">Conceptos Básicos de Action Mailer</option>
<option value="action_mailbox_basics.html">Conceptos Básicos de Action Mailbox</option>
<option value="action_text_overview.html">Resumen de Action Text</option>
<option value="active_job_basics.html">Conceptos Básicos de Active Job</option>
</optgroup>
<optgroup label="Políticas">
<option value="maintenance_policy.html">Política de Mantenimiento</option>
</optgroup>
<optgroup label="Notas de Lanzamiento">
<option value="upgrading_ruby_on_rails.html">Actualizando Ruby on Rails</option>
<option value="7_2_release_notes.html">Versión 7.2 - ?</option>
<option value="7_1_release_notes.html">Versión 7.1 - Octubre 2023</option>
<option value="7_0_release_notes.html">Versión 7.0 - Diciembre 2021</option>
<option value="6_1_release_notes.html">Versión 6.1 - Diciembre 2020</option>
</optgroup>
</select>
</li>
</ul>
</nav>
</div>
</header>
<hr class="hide" />
<section id="feature">
<div class="wrapper">
<p><strong>NO LEA ESTE ARCHIVO EN GITHUB, LAS GUÍAS ESTÁN PUBLICADAS EN <a href="https://guides.rubyonrails.org">https://guides.rubyonrails.org</a>.</strong></p><h1>El Proceso de Inicialización de Rails</h1><p>Esta guía explica los aspectos internos del proceso de inicialización en Rails.
Es una guía extremadamente detallada y se recomienda para desarrolladores avanzados de Rails.</p><p>Después de leer esta guía, sabrás:</p>
<ul>
<li>Cómo usar <code>bin/rails server</code>.</li>
<li>La secuencia temporal de la inicialización de Rails.</li>
<li>Dónde se requieren diferentes archivos en la secuencia de arranque.</li>
<li>Cómo se define y se utiliza la interfaz de Rails::Server.</li>
</ul>
<nav id="subCol">
<h3 class="chapter">
<picture>
<!-- Using the `source` HTML tag to set the dark theme image -->
<source
srcset="images/icon_book-close-bookmark-1-wht.svg"
media="(prefers-color-scheme: dark)"
/>
<img src="images/icon_book-close-bookmark-1.svg" alt="Chapter Icon" />
</picture>
Chapters
</h3>
<ol class="chapters">
<li><a href="#¡despegue-bang">¡Despegue!</a>
<ul>
<li><a href="#bin-rails"><code>bin/rails</code></a></li>
<li><a href="#config-boot-rb"><code>config/boot.rb</code></a></li>
<li><a href="#rails-commands-rb"><code>rails/commands.rb</code></a></li>
<li><a href="#rails-command-rb"><code>rails/command.rb</code></a></li>
<li><a href="#actionpack-lib-action-dispatch-rb"><code>actionpack/lib/action_dispatch.rb</code></a></li>
<li><a href="#rails-commands-server-server-command-rb"><code>rails/commands/server/server_command.rb</code></a></li>
<li><a href="#¡despegue-bang-rack-lib-rack-server-rb">Rack: <code>lib/rack/server.rb</code></a></li>
<li><a href="#config-application"><code>config/application</code></a></li>
<li><a href="#rails-server-start"><code>Rails::Server#start</code></a></li>
<li><a href="#config-environment-rb"><code>config/environment.rb</code></a></li>
<li><a href="#config-application-rb"><code>config/application.rb</code></a></li>
</ul></li>
<li><a href="#cargando-rails">Cargando Rails</a>
<ul>
<li><a href="#railties-lib-rails-all-rb"><code>railties/lib/rails/all.rb</code></a></li>
<li><a href="#volvamos-a-config-environment-rb">Volvamos a <code>config/environment.rb</code></a></li>
<li><a href="#railties-lib-rails-application-rb"><code>railties/lib/rails/application.rb</code></a></li>
<li><a href="#cargando-rails-rack-lib-rack-server-rb">Rack: lib/rack/server.rb</a></li>
</ul></li>
</ol>
</nav>
<hr>
</div>
</section>
<main id="container">
<div class="wrapper">
<div id="mainCol">
<p>Esta guía repasa cada llamada de método que es
necesaria para iniciar la pila de Ruby on Rails para una aplicación Rails por defecto, explicando cada parte en detalle a lo largo del camino. Para esta
guía, nos enfocaremos en lo que sucede cuando ejecutas <code>bin/rails server</code>
para iniciar tu aplicación.</p><p>NOTA: Las rutas en esta guía son relativas a Rails o a una aplicación Rails a menos que se especifique lo contrario.</p><p>CONSEJO: Si deseas seguir mientras navegas por el <a href="https://github.com/rails/rails">código fuente de Rails</a>, te recomendamos que uses la tecla <code>t</code>
para abrir el buscador de archivos dentro de GitHub y encontrar archivos
rápidamente.</p><h2 id="¡despegue-bang"><a class="anchorlink" href="#¡despegue-bang"><span>1</span> ¡Despegue!</a></h2><p>Comencemos a iniciar e inicializar la aplicación. Una aplicación Rails generalmente
se inicia ejecutando <code>bin/rails console</code> o <code>bin/rails server</code>.</p><h3 id="bin-rails"><a class="anchorlink" href="#bin-rails"><span>1.1</span> <code>bin/rails</code></a></h3><p>Este archivo es el siguiente:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="c1">#!/usr/bin/env ruby</span>
<span class="no">APP_PATH</span> <span class="o">=</span> <span class="no">File</span><span class="p">.</span><span class="nf">expand_path</span><span class="p">(</span><span class="s1">'../config/application'</span><span class="p">,</span> <span class="n">__dir__</span><span class="p">)</span>
<span class="nb">require_relative</span> <span class="s2">"../config/boot"</span>
<span class="nb">require</span> <span class="s2">"rails/commands"</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="#!/usr/bin/env ruby
APP_PATH = File.expand_path('../config/application', __dir__)
require_relative "../config/boot"
require "rails/commands"
">Copy</button>
</div>
<p>La constante <code>APP_PATH</code> se usará más adelante en <code>rails/commands</code>. El archivo <code>config/boot</code> referenciado aquí es el archivo <code>config/boot.rb</code> en nuestra aplicación que es responsable de cargar Bundler y configurarlo.</p><h3 id="config-boot-rb"><a class="anchorlink" href="#config-boot-rb"><span>1.2</span> <code>config/boot.rb</code></a></h3><p><code>config/boot.rb</code> contiene:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="no">ENV</span><span class="p">[</span><span class="s1">'BUNDLE_GEMFILE'</span><span class="p">]</span> <span class="o">||=</span> <span class="no">File</span><span class="p">.</span><span class="nf">expand_path</span><span class="p">(</span><span class="s1">'../Gemfile'</span><span class="p">,</span> <span class="n">__dir__</span><span class="p">)</span>
<span class="nb">require</span> <span class="s2">"bundler/setup"</span> <span class="c1"># Configura las gemas listadas en el Gemfile.</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__)
require "bundler/setup" # Configura las gemas listadas en el Gemfile.
">Copy</button>
</div>
<p>En una aplicación Rails estándar, hay un <code>Gemfile</code> que declara todas
las dependencias de la aplicación. <code>config/boot.rb</code> establece
<code>ENV['BUNDLE_GEMFILE']</code> en la ubicación de este archivo. Si el <code>Gemfile</code>
existe, entonces se requiere <code>bundler/setup</code>. El require es usado por Bundler para
configurar la ruta de carga para las dependencias de tu Gemfile.</p><h3 id="rails-commands-rb"><a class="anchorlink" href="#rails-commands-rb"><span>1.3</span> <code>rails/commands.rb</code></a></h3><p>Una vez que <code>config/boot.rb</code> ha terminado, el siguiente archivo que se requiere es
<code>rails/commands</code>, que ayuda a expandir alias. En el caso actual, el
array <code>ARGV</code> simplemente contiene <code>server</code>, que será pasado:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="nb">require</span> <span class="s2">"rails/command"</span>
<span class="n">aliases</span> <span class="o">=</span> <span class="p">{</span>
<span class="s2">"g"</span> <span class="o">=></span> <span class="s2">"generate"</span><span class="p">,</span>
<span class="s2">"d"</span> <span class="o">=></span> <span class="s2">"destroy"</span><span class="p">,</span>
<span class="s2">"c"</span> <span class="o">=></span> <span class="s2">"console"</span><span class="p">,</span>
<span class="s2">"s"</span> <span class="o">=></span> <span class="s2">"server"</span><span class="p">,</span>
<span class="s2">"db"</span> <span class="o">=></span> <span class="s2">"dbconsole"</span><span class="p">,</span>
<span class="s2">"r"</span> <span class="o">=></span> <span class="s2">"runner"</span><span class="p">,</span>
<span class="s2">"t"</span> <span class="o">=></span> <span class="s2">"test"</span>
<span class="p">}</span>
<span class="n">command</span> <span class="o">=</span> <span class="no">ARGV</span><span class="p">.</span><span class="nf">shift</span>
<span class="n">command</span> <span class="o">=</span> <span class="n">aliases</span><span class="p">[</span><span class="n">command</span><span class="p">]</span> <span class="o">||</span> <span class="n">command</span>
<span class="no">Rails</span><span class="o">::</span><span class="no">Command</span><span class="p">.</span><span class="nf">invoke</span> <span class="n">command</span><span class="p">,</span> <span class="no">ARGV</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="require "rails/command"
aliases = {
"g" => "generate",
"d" => "destroy",
"c" => "console",
"s" => "server",
"db" => "dbconsole",
"r" => "runner",
"t" => "test"
}
command = ARGV.shift
command = aliases[command] || command
Rails::Command.invoke command, ARGV
">Copy</button>
</div>
<p>Si hubiéramos usado <code>s</code> en lugar de <code>server</code>, Rails habría usado los <code>aliases</code>
definidos aquí para encontrar el comando correspondiente.</p><h3 id="rails-command-rb"><a class="anchorlink" href="#rails-command-rb"><span>1.4</span> <code>rails/command.rb</code></a></h3><p>Cuando uno escribe un comando de Rails, <code>invoke</code> intenta buscar un comando para el
espacio de nombres dado y ejecuta el comando si se encuentra.</p><p>Si Rails no reconoce el comando, le pasa el control a Rake
para ejecutar una tarea con el mismo nombre.</p><p>Como se muestra, <code>Rails::Command</code> muestra automáticamente la salida de ayuda si el <code>namespace</code>
está vacío.</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="k">module</span> <span class="nn">Rails</span>
<span class="k">module</span> <span class="nn">Command</span>
<span class="k">class</span> <span class="o"><<</span> <span class="nb">self</span>
<span class="k">def</span> <span class="nf">invoke</span><span class="p">(</span><span class="n">full_namespace</span><span class="p">,</span> <span class="n">args</span> <span class="o">=</span> <span class="p">[],</span> <span class="o">**</span><span class="n">config</span><span class="p">)</span>
<span class="n">namespace</span> <span class="o">=</span> <span class="n">full_namespace</span> <span class="o">=</span> <span class="n">full_namespace</span><span class="p">.</span><span class="nf">to_s</span>
<span class="k">if</span> <span class="n">char</span> <span class="o">=</span> <span class="n">namespace</span> <span class="o">=~</span> <span class="sr">/:(\w+)$/</span>
<span class="n">command_name</span><span class="p">,</span> <span class="n">namespace</span> <span class="o">=</span> <span class="vg">$1</span><span class="p">,</span> <span class="n">namespace</span><span class="p">.</span><span class="nf">slice</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">char</span><span class="p">)</span>
<span class="k">else</span>
<span class="n">command_name</span> <span class="o">=</span> <span class="n">namespace</span>
<span class="k">end</span>
<span class="n">command_name</span><span class="p">,</span> <span class="n">namespace</span> <span class="o">=</span> <span class="s2">"help"</span><span class="p">,</span> <span class="s2">"help"</span> <span class="k">if</span> <span class="n">command_name</span><span class="p">.</span><span class="nf">blank?</span> <span class="o">||</span> <span class="no">HELP_MAPPINGS</span><span class="p">.</span><span class="nf">include?</span><span class="p">(</span><span class="n">command_name</span><span class="p">)</span>
<span class="n">command_name</span><span class="p">,</span> <span class="n">namespace</span> <span class="o">=</span> <span class="s2">"version"</span><span class="p">,</span> <span class="s2">"version"</span> <span class="k">if</span> <span class="sx">%w( -v --version )</span><span class="p">.</span><span class="nf">include?</span><span class="p">(</span><span class="n">command_name</span><span class="p">)</span>
<span class="n">command</span> <span class="o">=</span> <span class="n">find_by_namespace</span><span class="p">(</span><span class="n">namespace</span><span class="p">,</span> <span class="n">command_name</span><span class="p">)</span>
<span class="k">if</span> <span class="n">command</span> <span class="o">&&</span> <span class="n">command</span><span class="p">.</span><span class="nf">all_commands</span><span class="p">[</span><span class="n">command_name</span><span class="p">]</span>
<span class="n">command</span><span class="p">.</span><span class="nf">perform</span><span class="p">(</span><span class="n">command_name</span><span class="p">,</span> <span class="n">args</span><span class="p">,</span> <span class="n">config</span><span class="p">)</span>
<span class="k">else</span>
<span class="n">find_by_namespace</span><span class="p">(</span><span class="s2">"rake"</span><span class="p">).</span><span class="nf">perform</span><span class="p">(</span><span class="n">full_namespace</span><span class="p">,</span> <span class="n">args</span><span class="p">,</span> <span class="n">config</span><span class="p">)</span>
<span class="k">end</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="module Rails
module Command
class << self
def invoke(full_namespace, args = [], **config)
namespace = full_namespace = full_namespace.to_s
if char = namespace =~ /:(\w+)$/
command_name, namespace = $1, namespace.slice(0, char)
else
command_name = namespace
end
command_name, namespace = "help", "help" if command_name.blank? || HELP_MAPPINGS.include?(command_name)
command_name, namespace = "version", "version" if %w( -v --version ).include?(command_name)
command = find_by_namespace(namespace, command_name)
if command && command.all_commands[command_name]
command.perform(command_name, args, config)
else
find_by_namespace("rake").perform(full_namespace, args, config)
end
end
end
end
end
">Copy</button>
</div>
<p>Con el comando <code>server</code>, Rails ejecutará el siguiente código:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="k">module</span> <span class="nn">Rails</span>
<span class="k">module</span> <span class="nn">Command</span>
<span class="k">class</span> <span class="nc">ServerCommand</span> <span class="o"><</span> <span class="no">Base</span> <span class="c1"># :nodoc:</span>
<span class="k">def</span> <span class="nf">perform</span>
<span class="n">extract_environment_option_from_argument</span>
<span class="n">set_application_directory!</span>
<span class="n">prepare_restart</span>
<span class="no">Rails</span><span class="o">::</span><span class="no">Server</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="n">server_options</span><span class="p">).</span><span class="nf">tap</span> <span class="k">do</span> <span class="o">|</span><span class="n">server</span><span class="o">|</span>
<span class="c1"># Requerir la aplicación después de que el servidor establezca el entorno para propagar</span>
<span class="c1"># la opción --environment.</span>
<span class="nb">require</span> <span class="no">APP_PATH</span>
<span class="no">Dir</span><span class="p">.</span><span class="nf">chdir</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">root</span><span class="p">)</span>
<span class="k">if</span> <span class="n">server</span><span class="p">.</span><span class="nf">serveable?</span>
<span class="n">print_boot_information</span><span class="p">(</span><span class="n">server</span><span class="p">.</span><span class="nf">server</span><span class="p">,</span> <span class="n">server</span><span class="p">.</span><span class="nf">served_url</span><span class="p">)</span>
<span class="n">after_stop_callback</span> <span class="o">=</span> <span class="o">-></span> <span class="p">{</span> <span class="n">say</span> <span class="s2">"Exiting"</span> <span class="k">unless</span> <span class="n">options</span><span class="p">[</span><span class="ss">:daemon</span><span class="p">]</span> <span class="p">}</span>
<span class="n">server</span><span class="p">.</span><span class="nf">start</span><span class="p">(</span><span class="n">after_stop_callback</span><span class="p">)</span>
<span class="k">else</span>
<span class="n">say</span> <span class="n">rack_server_suggestion</span><span class="p">(</span><span class="n">using</span><span class="p">)</span>
<span class="k">end</span>
<span class="k">end</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="module Rails
module Command
class ServerCommand < Base # :nodoc:
def perform
extract_environment_option_from_argument
set_application_directory!
prepare_restart
Rails::Server.new(server_options).tap do |server|
# Requerir la aplicación después de que el servidor establezca el entorno para propagar
# la opción --environment.
require APP_PATH
Dir.chdir(Rails.application.root)
if server.serveable?
print_boot_information(server.server, server.served_url)
after_stop_callback = -> { say "Exiting" unless options[:daemon] }
server.start(after_stop_callback)
else
say rack_server_suggestion(using)
end
end
end
end
end
end
">Copy</button>
</div>
<p>Este archivo cambiará al directorio raíz de Rails (una ruta dos directorios arriba
de <code>APP_PATH</code>, que apunta a <code>config/application.rb</code>), pero solo si el
archivo <code>config.ru</code> no se encuentra. Esto luego inicia la clase <code>Rails::Server</code>.</p><h3 id="actionpack-lib-action-dispatch-rb"><a class="anchorlink" href="#actionpack-lib-action-dispatch-rb"><span>1.5</span> <code>actionpack/lib/action_dispatch.rb</code></a></h3><p>Action Dispatch es el componente de enrutamiento del marco de Rails.
Añade funcionalidades como enrutamiento, sesión y middlewares comunes.</p><h3 id="rails-commands-server-server-command-rb"><a class="anchorlink" href="#rails-commands-server-server-command-rb"><span>1.6</span> <code>rails/commands/server/server_command.rb</code></a></h3><p>La clase <code>Rails::Server</code> se define en este archivo heredando de
<code>Rack::Server</code>. Cuando se llama a <code>Rails::Server.new</code>, esto llama al método <code>initialize</code>
en <code>rails/commands/server/server_command.rb</code>:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="k">module</span> <span class="nn">Rails</span>
<span class="k">class</span> <span class="nc">Server</span> <span class="o"><</span> <span class="o">::</span><span class="no">Rack</span><span class="o">::</span><span class="no">Server</span>
<span class="k">def</span> <span class="nf">initialize</span><span class="p">(</span><span class="n">options</span> <span class="o">=</span> <span class="kp">nil</span><span class="p">)</span>
<span class="vi">@default_options</span> <span class="o">=</span> <span class="n">options</span> <span class="o">||</span> <span class="p">{}</span>
<span class="k">super</span><span class="p">(</span><span class="vi">@default_options</span><span class="p">)</span>
<span class="n">set_environment</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 Rails
class Server < ::Rack::Server
def initialize(options = nil)
@default_options = options || {}
super(@default_options)
set_environment
end
end
end
">Copy</button>
</div>
<p>Primero, se llama a <code>super</code>, que llama al método <code>initialize</code> en <code>Rack::Server</code>.</p><h3 id="¡despegue-bang-rack-lib-rack-server-rb"><a class="anchorlink" href="#¡despegue-bang-rack-lib-rack-server-rb"><span>1.7</span> Rack: <code>lib/rack/server.rb</code></a></h3><p><code>Rack::Server</code> es responsable de proporcionar una interfaz de servidor común para todas las aplicaciones basadas en Rack, de las cuales Rails ahora forma parte.</p><p>El método <code>initialize</code> en <code>Rack::Server</code> simplemente establece varias variables:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="k">module</span> <span class="nn">Rack</span>
<span class="k">class</span> <span class="nc">Server</span>
<span class="k">def</span> <span class="nf">initialize</span><span class="p">(</span><span class="n">options</span> <span class="o">=</span> <span class="kp">nil</span><span class="p">)</span>
<span class="vi">@ignore_options</span> <span class="o">=</span> <span class="p">[]</span>
<span class="k">if</span> <span class="n">options</span>
<span class="vi">@use_default_options</span> <span class="o">=</span> <span class="kp">false</span>
<span class="vi">@options</span> <span class="o">=</span> <span class="n">options</span>
<span class="vi">@app</span> <span class="o">=</span> <span class="n">options</span><span class="p">[</span><span class="ss">:app</span><span class="p">]</span> <span class="k">if</span> <span class="n">options</span><span class="p">[</span><span class="ss">:app</span><span class="p">]</span>
<span class="k">else</span>
<span class="n">argv</span> <span class="o">=</span> <span class="k">defined?</span><span class="p">(</span><span class="no">SPEC_ARGV</span><span class="p">)</span> <span class="p">?</span> <span class="no">SPEC_ARGV</span> <span class="p">:</span> <span class="no">ARGV</span>
<span class="vi">@use_default_options</span> <span class="o">=</span> <span class="kp">true</span>
<span class="vi">@options</span> <span class="o">=</span> <span class="n">parse_options</span><span class="p">(</span><span class="n">argv</span><span class="p">)</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="module Rack
class Server
def initialize(options = nil)
@ignore_options = []
if options
@use_default_options = false
@options = options
@app = options[:app] if options[:app]
else
argv = defined?(SPEC_ARGV) ? SPEC_ARGV : ARGV
@use_default_options = true
@options = parse_options(argv)
end
end
end
end
">Copy</button>
</div>
<p>En este caso, el valor de retorno de <code>Rails::Command::ServerCommand#server_options</code> se asignará a <code>options</code>.
Cuando se evalúan las líneas dentro de la declaración if, se establecerán un par de variables de instancia.</p><p>El método <code>server_options</code> en <code>Rails::Command::ServerCommand</code> se define de la siguiente manera:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="k">module</span> <span class="nn">Rails</span>
<span class="k">module</span> <span class="nn">Command</span>
<span class="k">class</span> <span class="nc">ServerCommand</span>
<span class="n">no_commands</span> <span class="k">do</span>
<span class="k">def</span> <span class="nf">server_options</span>
<span class="p">{</span>
<span class="ss">user_supplied_options: </span><span class="n">user_supplied_options</span><span class="p">,</span>
<span class="ss">server: </span><span class="n">using</span><span class="p">,</span>
<span class="ss">log_stdout: </span><span class="n">log_to_stdout?</span><span class="p">,</span>
<span class="no">Port</span><span class="p">:</span> <span class="n">port</span><span class="p">,</span>
<span class="no">Host</span><span class="p">:</span> <span class="n">host</span><span class="p">,</span>
<span class="no">DoNotReverseLookup</span><span class="p">:</span> <span class="kp">true</span><span class="p">,</span>
<span class="ss">config: </span><span class="n">options</span><span class="p">[</span><span class="ss">:config</span><span class="p">],</span>
<span class="ss">environment: </span><span class="n">environment</span><span class="p">,</span>
<span class="ss">daemonize: </span><span class="n">options</span><span class="p">[</span><span class="ss">:daemon</span><span class="p">],</span>
<span class="ss">pid: </span><span class="n">pid</span><span class="p">,</span>
<span class="ss">caching: </span><span class="n">options</span><span class="p">[</span><span class="ss">:dev_caching</span><span class="p">],</span>
<span class="ss">restart_cmd: </span><span class="n">restart_command</span><span class="p">,</span>
<span class="ss">early_hints: </span><span class="n">early_hints</span>
<span class="p">}</span>
<span class="k">end</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="module Rails
module Command
class ServerCommand
no_commands do
def server_options
{
user_supplied_options: user_supplied_options,
server: using,
log_stdout: log_to_stdout?,
Port: port,
Host: host,
DoNotReverseLookup: true,
config: options[:config],
environment: environment,
daemonize: options[:daemon],
pid: pid,
caching: options[:dev_caching],
restart_cmd: restart_command,
early_hints: early_hints
}
end
end
end
end
end
">Copy</button>
</div>
<p>El valor se asignará a la variable de instancia <code>@options</code>.</p><p>Después de que <code>super</code> haya terminado en <code>Rack::Server</code>, volvemos a
<code>rails/commands/server/server_command.rb</code>. En este punto, se llama a <code>set_environment</code>
dentro del contexto del objeto <code>Rails::Server</code>.</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="k">module</span> <span class="nn">Rails</span>
<span class="k">module</span> <span class="nn">Server</span>
<span class="k">def</span> <span class="nf">set_environment</span>
<span class="no">ENV</span><span class="p">[</span><span class="s2">"RAILS_ENV"</span><span class="p">]</span> <span class="o">||=</span> <span class="n">options</span><span class="p">[</span><span class="ss">:environment</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="module Rails
module Server
def set_environment
ENV["RAILS_ENV"] ||= options[:environment]
end
end
end
">Copy</button>
</div>
<p>Después de que <code>initialize</code> haya terminado, volvemos al comando del servidor
donde se requiere <code>APP_PATH</code> (que se estableció anteriormente).</p><h3 id="config-application"><a class="anchorlink" href="#config-application"><span>1.8</span> <code>config/application</code></a></h3><p>Cuando se ejecuta <code>require APP_PATH</code>, se carga <code>config/application.rb</code> (recuerda
que <code>APP_PATH</code> se define en <code>bin/rails</code>). Este archivo existe en tu aplicación
y eres libre de cambiarlo según tus necesidades.</p><h3 id="rails-server-start"><a class="anchorlink" href="#rails-server-start"><span>1.9</span> <code>Rails::Server#start</code></a></h3><p>Después de que se carga <code>config/application</code>, se llama a <code>server.start</code>. Este método se
define así:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="k">module</span> <span class="nn">Rails</span>
<span class="k">class</span> <span class="nc">Server</span> <span class="o"><</span> <span class="o">::</span><span class="no">Rack</span><span class="o">::</span><span class="no">Server</span>
<span class="k">def</span> <span class="nf">start</span><span class="p">(</span><span class="n">after_stop_callback</span> <span class="o">=</span> <span class="kp">nil</span><span class="p">)</span>
<span class="nb">trap</span><span class="p">(</span><span class="ss">:INT</span><span class="p">)</span> <span class="p">{</span> <span class="nb">exit</span> <span class="p">}</span>
<span class="n">create_tmp_directories</span>
<span class="n">setup_dev_caching</span>
<span class="n">log_to_stdout</span> <span class="k">if</span> <span class="n">options</span><span class="p">[</span><span class="ss">:log_stdout</span><span class="p">]</span>
<span class="k">super</span><span class="p">()</span>
<span class="c1"># ...</span>
<span class="k">end</span>
<span class="kp">private</span>
<span class="k">def</span> <span class="nf">setup_dev_caching</span>
<span class="k">if</span> <span class="n">options</span><span class="p">[</span><span class="ss">:environment</span><span class="p">]</span> <span class="o">==</span> <span class="s2">"development"</span>
<span class="no">Rails</span><span class="o">::</span><span class="no">DevCaching</span><span class="p">.</span><span class="nf">enable_by_argument</span><span class="p">(</span><span class="n">options</span><span class="p">[</span><span class="ss">:caching</span><span class="p">])</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">create_tmp_directories</span>
<span class="sx">%w(cache pids sockets)</span><span class="p">.</span><span class="nf">each</span> <span class="k">do</span> <span class="o">|</span><span class="n">dir_to_make</span><span class="o">|</span>
<span class="no">FileUtils</span><span class="p">.</span><span class="nf">mkdir_p</span><span class="p">(</span><span class="no">File</span><span class="p">.</span><span class="nf">join</span><span class="p">(</span><span class="no">Rails</span><span class="p">.</span><span class="nf">root</span><span class="p">,</span> <span class="s2">"tmp"</span><span class="p">,</span> <span class="n">dir_to_make</span><span class="p">))</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">log_to_stdout</span>
<span class="n">wrapped_app</span> <span class="c1"># toca la aplicación para que el logger esté configurado</span>
<span class="n">console</span> <span class="o">=</span> <span class="no">ActiveSupport</span><span class="o">::</span><span class="no">Logger</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="no">STDOUT</span><span class="p">)</span>
<span class="n">console</span><span class="p">.</span><span class="nf">formatter</span> <span class="o">=</span> <span class="no">Rails</span><span class="p">.</span><span class="nf">logger</span><span class="p">.</span><span class="nf">formatter</span>
<span class="n">console</span><span class="p">.</span><span class="nf">level</span> <span class="o">=</span> <span class="no">Rails</span><span class="p">.</span><span class="nf">logger</span><span class="p">.</span><span class="nf">level</span>
<span class="k">unless</span> <span class="no">ActiveSupport</span><span class="o">::</span><span class="no">Logger</span><span class="p">.</span><span class="nf">logger_outputs_to?</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="no">STDOUT</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">extend</span><span class="p">(</span><span class="no">ActiveSupport</span><span class="o">::</span><span class="no">Logger</span><span class="p">.</span><span class="nf">broadcast</span><span class="p">(</span><span class="n">console</span><span class="p">))</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="module Rails
class Server < ::Rack::Server
def start(after_stop_callback = nil)
trap(:INT) { exit }
create_tmp_directories
setup_dev_caching
log_to_stdout if options[:log_stdout]
super()
# ...
end
private
def setup_dev_caching
if options[:environment] == "development"
Rails::DevCaching.enable_by_argument(options[:caching])
end
end
def create_tmp_directories
%w(cache pids sockets).each do |dir_to_make|
FileUtils.mkdir_p(File.join(Rails.root, "tmp", dir_to_make))
end
end
def log_to_stdout
wrapped_app # toca la aplicación para que el logger esté configurado
console = ActiveSupport::Logger.new(STDOUT)
console.formatter = Rails.logger.formatter
console.level = Rails.logger.level
unless ActiveSupport::Logger.logger_outputs_to?(Rails.logger, STDOUT)
Rails.logger.extend(ActiveSupport::Logger.broadcast(console))
end
end
end
end
">Copy</button>
</div>
<p>Este método crea una trampa para señales <code>INT</code>, por lo que si presionas <code>CTRL-C</code> en el servidor, saldrá del proceso.
Como podemos ver en el código aquí, creará los directorios <code>tmp/cache</code>,
<code>tmp/pids</code> y <code>tmp/sockets</code>. Luego habilita la caché en desarrollo
si <code>bin/rails server</code> se llama con <code>--dev-caching</code>. Finalmente, llama a <code>wrapped_app</code>, que es
responsable de crear la aplicación Rack, antes de crear y asignar una instancia
de <code>ActiveSupport::Logger</code>.</p><p>El método <code>super</code> llamará a <code>Rack::Server.start</code>, que comienza su definición como sigue:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="k">module</span> <span class="nn">Rack</span>
<span class="k">class</span> <span class="nc">Server</span>
<span class="k">def</span> <span class="nf">start</span><span class="p">(</span><span class="o">&</span><span class="n">blk</span><span class="p">)</span>
<span class="k">if</span> <span class="n">options</span><span class="p">[</span><span class="ss">:warn</span><span class="p">]</span>
<span class="vg">$-w</span> <span class="o">=</span> <span class="kp">true</span>
<span class="k">end</span>
<span class="k">if</span> <span class="n">includes</span> <span class="o">=</span> <span class="n">options</span><span class="p">[</span><span class="ss">:include</span><span class="p">]</span>
<span class="vg">$LOAD_PATH</span><span class="p">.</span><span class="nf">unshift</span><span class="p">(</span><span class="o">*</span><span class="n">includes</span><span class="p">)</span>
<span class="k">end</span>
<span class="k">if</span> <span class="n">library</span> <span class="o">=</span> <span class="n">options</span><span class="p">[</span><span class="ss">:require</span><span class="p">]</span>
<span class="nb">require</span> <span class="n">library</span>
<span class="k">end</span>
<span class="k">if</span> <span class="n">options</span><span class="p">[</span><span class="ss">:debug</span><span class="p">]</span>
<span class="vg">$DEBUG</span> <span class="o">=</span> <span class="kp">true</span>
<span class="nb">require</span> <span class="s2">"pp"</span>
<span class="nb">p</span> <span class="n">options</span><span class="p">[</span><span class="ss">:server</span><span class="p">]</span>
<span class="n">pp</span> <span class="n">wrapped_app</span>
<span class="n">pp</span> <span class="n">app</span>
<span class="k">end</span>
<span class="n">check_pid!</span> <span class="k">if</span> <span class="n">options</span><span class="p">[</span><span class="ss">:pid</span><span class="p">]</span>
<span class="c1"># Toca la aplicación envuelta, para que config.ru se cargue antes de</span>
<span class="c1"># la demonización (es decir, antes de chdir, etc.).</span>
<span class="n">handle_profiling</span><span class="p">(</span><span class="n">options</span><span class="p">[</span><span class="ss">:heapfile</span><span class="p">],</span> <span class="n">options</span><span class="p">[</span><span class="ss">:profile_mode</span><span class="p">],</span> <span class="n">options</span><span class="p">[</span><span class="ss">:profile_file</span><span class="p">])</span> <span class="k">do</span>
<span class="n">wrapped_app</span>
<span class="k">end</span>
<span class="n">daemonize_app</span> <span class="k">if</span> <span class="n">options</span><span class="p">[</span><span class="ss">:daemonize</span><span class="p">]</span>
<span class="n">write_pid</span> <span class="k">if</span> <span class="n">options</span><span class="p">[</span><span class="ss">:pid</span><span class="p">]</span>
<span class="nb">trap</span><span class="p">(</span><span class="ss">:INT</span><span class="p">)</span> <span class="k">do</span>
<span class="k">if</span> <span class="n">server</span><span class="p">.</span><span class="nf">respond_to?</span><span class="p">(</span><span class="ss">:shutdown</span><span class="p">)</span>
<span class="n">server</span><span class="p">.</span><span class="nf">shutdown</span>
<span class="k">else</span>
<span class="nb">exit</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="n">server</span><span class="p">.</span><span class="nf">run</span> <span class="n">wrapped_app</span><span class="p">,</span> <span class="n">options</span><span class="p">,</span> <span class="o">&</span><span class="n">blk</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 Rack
class Server
def start(&blk)
if options[:warn]
$-w = true
end
if includes = options[:include]
$LOAD_PATH.unshift(*includes)
end
if library = options[:require]
require library
end
if options[:debug]
$DEBUG = true
require "pp"
p options[:server]
pp wrapped_app
pp app
end
check_pid! if options[:pid]
# Toca la aplicación envuelta, para que config.ru se cargue antes de
# la demonización (es decir, antes de chdir, etc.).
handle_profiling(options[:heapfile], options[:profile_mode], options[:profile_file]) do
wrapped_app
end
daemonize_app if options[:daemonize]
write_pid if options[:pid]
trap(:INT) do
if server.respond_to?(:shutdown)
server.shutdown
else
exit
end
end
server.run wrapped_app, options, &blk
end
end
end
">Copy</button>
</div>
<p>La parte interesante para una aplicación Rails es la última línea, <code>server.run</code>. Aquí encontramos nuevamente el método <code>wrapped_app</code>, que esta vez
vamos a explorar más (aunque ya se ejecutó antes, y
por lo tanto, ya está memorizado).</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="k">module</span> <span class="nn">Rack</span>
<span class="k">class</span> <span class="nc">Server</span>
<span class="k">def</span> <span class="nf">wrapped_app</span>
<span class="vi">@wrapped_app</span> <span class="o">||=</span> <span class="n">build_app</span> <span class="n">app</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 Rack
class Server
def wrapped_app
@wrapped_app ||= build_app app
end
end
end
">Copy</button>
</div>
<p>El método <code>app</code> aquí se define así:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="k">module</span> <span class="nn">Rack</span>
<span class="k">class</span> <span class="nc">Server</span>
<span class="k">def</span> <span class="nf">app</span>
<span class="vi">@app</span> <span class="o">||=</span> <span class="n">options</span><span class="p">[</span><span class="ss">:builder</span><span class="p">]</span> <span class="p">?</span> <span class="n">build_app_from_string</span> <span class="p">:</span> <span class="n">build_app_and_options_from_config</span>
<span class="k">end</span>
<span class="c1"># ...</span>
<span class="kp">private</span>
<span class="k">def</span> <span class="nf">build_app_and_options_from_config</span>
<span class="k">if</span> <span class="o">!::</span><span class="no">File</span><span class="p">.</span><span class="nf">exist?</span> <span class="n">options</span><span class="p">[</span><span class="ss">:config</span><span class="p">]</span>
<span class="nb">abort</span> <span class="s2">"configuration </span><span class="si">#{</span><span class="n">options</span><span class="p">[</span><span class="ss">:config</span><span class="p">]</span><span class="si">}</span><span class="s2"> not found"</span>
<span class="k">end</span>
<span class="n">app</span><span class="p">,</span> <span class="n">options</span> <span class="o">=</span> <span class="no">Rack</span><span class="o">::</span><span class="no">Builder</span><span class="p">.</span><span class="nf">parse_file</span><span class="p">(</span><span class="nb">self</span><span class="p">.</span><span class="nf">options</span><span class="p">[</span><span class="ss">:config</span><span class="p">],</span> <span class="n">opt_parser</span><span class="p">)</span>
<span class="vi">@options</span><span class="p">.</span><span class="nf">merge!</span><span class="p">(</span><span class="n">options</span><span class="p">)</span> <span class="p">{</span> <span class="o">|</span><span class="n">key</span><span class="p">,</span> <span class="n">old</span><span class="p">,</span> <span class="n">new</span><span class="o">|</span> <span class="n">old</span> <span class="p">}</span>
<span class="n">app</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">build_app_from_string</span>
<span class="no">Rack</span><span class="o">::</span><span class="no">Builder</span><span class="p">.</span><span class="nf">new_from_string</span><span class="p">(</span><span class="nb">self</span><span class="p">.</span><span class="nf">options</span><span class="p">[</span><span class="ss">:builder</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="module Rack
class Server
def app
@app ||= options[:builder] ? build_app_from_string : build_app_and_options_from_config
end
# ...
private
def build_app_and_options_from_config
if !::File.exist? options[:config]
abort "configuration #{options[:config]} not found"
end
app, options = Rack::Builder.parse_file(self.options[:config], opt_parser)
@options.merge!(options) { |key, old, new| old }
app
end
def build_app_from_string
Rack::Builder.new_from_string(self.options[:builder])
end
end
end
">Copy</button>
</div>
<p>El valor de <code>options[:config]</code> por defecto es <code>config.ru</code>, que contiene esto:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="c1"># Este archivo es usado por servidores basados en Rack para iniciar la aplicación.</span>
<span class="nb">require_relative</span> <span class="s2">"config/environment"</span>
<span class="n">run</span> <span class="no">Rails</span><span class="p">.</span><span class="nf">application</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="# Este archivo es usado por servidores basados en Rack para iniciar la aplicación.
require_relative "config/environment"
run Rails.application
">Copy</button>
</div>
<p>El método <code>Rack::Builder.parse_file</code> aquí toma el contenido de este archivo <code>config.ru</code> y lo analiza usando este código:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="k">module</span> <span class="nn">Rack</span>
<span class="k">class</span> <span class="nc">Builder</span>
<span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">load_file</span><span class="p">(</span><span class="n">path</span><span class="p">,</span> <span class="n">opts</span> <span class="o">=</span> <span class="no">Server</span><span class="o">::</span><span class="no">Options</span><span class="p">.</span><span class="nf">new</span><span class="p">)</span>
<span class="c1"># ...</span>
<span class="n">app</span> <span class="o">=</span> <span class="n">new_from_string</span> <span class="n">cfgfile</span><span class="p">,</span> <span class="n">config</span>
<span class="c1"># ...</span>
<span class="k">end</span>
<span class="c1"># ...</span>
<span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">new_from_string</span><span class="p">(</span><span class="n">builder_script</span><span class="p">,</span> <span class="n">file</span> <span class="o">=</span> <span class="s2">"(rackup)"</span><span class="p">)</span>
<span class="nb">eval</span> <span class="s2">"Rack::Builder.new {</span><span class="se">\n</span><span class="s2">"</span> <span class="o">+</span> <span class="n">builder_script</span> <span class="o">+</span> <span class="s2">"</span><span class="se">\n</span><span class="s2">}.to_app"</span><span class="p">,</span>
<span class="no">TOPLEVEL_BINDING</span><span class="p">,</span> <span class="n">file</span><span class="p">,</span> <span class="mi">0</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 Rack
class Builder
def self.load_file(path, opts = Server::Options.new)
# ...
app = new_from_string cfgfile, config
# ...
end
# ...
def self.new_from_string(builder_script, file = "(rackup)")
eval "Rack::Builder.new {\n" + builder_script + "\n}.to_app",
TOPLEVEL_BINDING, file, 0
end
end
end
">Copy</button>
</div>
<p>El método <code>initialize</code> de <code>Rack::Builder</code> tomará el bloque aquí y lo ejecutará dentro de una instancia de <code>Rack::Builder</code>.
Aquí es donde ocurre la mayor parte del proceso de inicialización de Rails.
La línea <code>require</code> para <code>config/environment.rb</code> en <code>config.ru</code> es la primera en ejecutarse:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="nb">require_relative</span> <span class="s2">"config/environment"</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="require_relative "config/environment"
">Copy</button>
</div>
<h3 id="config-environment-rb"><a class="anchorlink" href="#config-environment-rb"><span>1.10</span> <code>config/environment.rb</code></a></h3><p>Este archivo es el archivo común requerido por <code>config.ru</code> (<code>bin/rails server</code>) y Passenger. Aquí es donde estos dos métodos para ejecutar el servidor se encuentran; todo lo anterior a este punto ha sido configuración de Rack y Rails.</p><p>Este archivo comienza requiriendo <code>config/application.rb</code>:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="nb">require_relative</span> <span class="s2">"application"</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="require_relative "application"
">Copy</button>
</div>
<h3 id="config-application-rb"><a class="anchorlink" href="#config-application-rb"><span>1.11</span> <code>config/application.rb</code></a></h3><p>Este archivo requiere <code>config/boot.rb</code>:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="nb">require_relative</span> <span class="s2">"boot"</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="require_relative "boot"
">Copy</button>
</div>
<p>Pero solo si no se ha requerido antes, lo cual sería el caso en <code>bin/rails server</code>
pero <strong>no</strong> sería el caso con Passenger.</p><p>¡Entonces comienza la diversión!</p><h2 id="cargando-rails"><a class="anchorlink" href="#cargando-rails"><span>2</span> Cargando Rails</a></h2><p>La siguiente línea en <code>config/application.rb</code> es:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="nb">require</span> <span class="s2">"rails/all"</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="require "rails/all"
">Copy</button>
</div>
<h3 id="railties-lib-rails-all-rb"><a class="anchorlink" href="#railties-lib-rails-all-rb"><span>2.1</span> <code>railties/lib/rails/all.rb</code></a></h3><p>Este archivo es responsable de requerir todos los marcos individuales de Rails:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="nb">require</span> <span class="s2">"rails"</span>
<span class="sx">%w(
active_record/railtie
active_storage/engine
action_controller/railtie
action_view/railtie
action_mailer/railtie
active_job/railtie
action_cable/engine
action_mailbox/engine
action_text/engine
rails/test_unit/railtie
)</span><span class="p">.</span><span class="nf">each</span> <span class="k">do</span> <span class="o">|</span><span class="n">railtie</span><span class="o">|</span>
<span class="k">begin</span>
<span class="nb">require</span> <span class="n">railtie</span>
<span class="k">rescue</span> <span class="no">LoadError</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="require "rails"
%w(
active_record/railtie
active_storage/engine
action_controller/railtie
action_view/railtie
action_mailer/railtie
active_job/railtie
action_cable/engine
action_mailbox/engine
action_text/engine
rails/test_unit/railtie
).each do |railtie|
begin
require railtie
rescue LoadError
end
end
">Copy</button>
</div>
<p>Aquí es donde se cargan todos los marcos de Rails y, por lo tanto, se hacen
disponibles para la aplicación. No entraremos en detalle sobre lo que sucede
dentro de cada uno de esos marcos, pero se te anima a intentar
explorarlos por tu cuenta.</p><p>Por ahora, solo ten en cuenta que funcionalidades comunes como motores de Rails,
I18n y configuración de Rails se están definiendo aquí.</p><h3 id="volvamos-a-config-environment-rb"><a class="anchorlink" href="#volvamos-a-config-environment-rb"><span>2.2</span> Volvamos a <code>config/environment.rb</code></a></h3><p>El resto de <code>config/application.rb</code> define la configuración para el
<code>Rails::Application</code>, que se usará una vez que la aplicación esté completamente
inicializada. Cuando <code>config/application.rb</code> ha terminado de cargar Rails y ha definido
el espacio de nombres de la aplicación, volvemos a <code>config/environment.rb</code>. Aquí, la
aplicación se inicializa con <code>Rails.application.initialize!</code>, que se
define en <code>rails/application.rb</code>.</p><h3 id="railties-lib-rails-application-rb"><a class="anchorlink" href="#railties-lib-rails-application-rb"><span>2.3</span> <code>railties/lib/rails/application.rb</code></a></h3><p>El método <code>initialize!</code> se ve así:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="k">def</span> <span class="nf">initialize!</span><span class="p">(</span><span class="n">group</span> <span class="o">=</span> <span class="ss">:default</span><span class="p">)</span> <span class="c1"># :nodoc:</span>
<span class="k">raise</span> <span class="s2">"Application has been already initialized."</span> <span class="k">if</span> <span class="vi">@initialized</span>
<span class="n">run_initializers</span><span class="p">(</span><span class="n">group</span><span class="p">,</span> <span class="nb">self</span><span class="p">)</span>
<span class="vi">@initialized</span> <span class="o">=</span> <span class="kp">true</span>
<span class="nb">self</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="def initialize!(group = :default) # :nodoc:
raise "Application has been already initialized." if @initialized
run_initializers(group, self)
@initialized = true
self
end
">Copy</button>
</div>
<p>Solo puedes inicializar una aplicación una vez. Los <a href="configuring.html#initializers">inicializadores</a> de Railtie
se ejecutan a través del método <code>run_initializers</code>, que se define en
<code>railties/lib/rails/initializable.rb</code>:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="k">def</span> <span class="nf">run_initializers</span><span class="p">(</span><span class="n">group</span> <span class="o">=</span> <span class="ss">:default</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">)</span>
<span class="k">return</span> <span class="k">if</span> <span class="n">instance_variable_defined?</span><span class="p">(</span><span class="ss">:@ran</span><span class="p">)</span>
<span class="n">initializers</span><span class="p">.</span><span class="nf">tsort_each</span> <span class="k">do</span> <span class="o">|</span><span class="n">initializer</span><span class="o">|</span>
<span class="n">initializer</span><span class="p">.</span><span class="nf">run</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span> <span class="k">if</span> <span class="n">initializer</span><span class="p">.</span><span class="nf">belongs_to?</span><span class="p">(</span><span class="n">group</span><span class="p">)</span>
<span class="k">end</span>
<span class="vi">@ran</span> <span class="o">=</span> <span class="kp">true</span>
<span class="k">end</span>
</code></pre>
<button class="clipboard-button" data-clipboard-text="def run_initializers(group = :default, *args)
return if instance_variable_defined?(:@ran)
initializers.tsort_each do |initializer|
initializer.run(*args) if initializer.belongs_to?(group)
end
@ran = true
end
">Copy</button>
</div>
<p>El código de <code>run_initializers</code> en sí es complicado. Lo que Rails está haciendo aquí es
recorrer todos los ancestros de la clase buscando aquellos que respondan a un
método <code>initializers</code>. Luego ordena los ancestros por nombre y los ejecuta.
Por ejemplo, la clase <code>Engine</code> hará que todos los motores estén disponibles al
proporcionar un método <code>initializers</code> en ellos.</p><p>La clase <code>Rails::Application</code>, tal como se define en <code>railties/lib/rails/application.rb</code>
define los inicializadores <code>bootstrap</code>, <code>railtie</code> y <code>finisher</code>. Los inicializadores <code>bootstrap</code>
preparan la aplicación (como inicializar el logger), mientras que los inicializadores <code>finisher</code>
(como construir la pila de middleware) se ejecutan al final. Los inicializadores <code>railtie</code>
son los inicializadores que se han definido en el propio <code>Rails::Application</code> y se ejecutan entre los <code>bootstrap</code> y los <code>finishers</code>.</p><p>NOTA: No confundas los inicializadores de Railtie en general con el <a href="configuring.html#using-initializer-files">initializer</a>
instance de inicializadores o sus inicializadores de configuración asociados en <code>config/initializers</code>.</p><p>Después de que esto se hace, volvemos a <code>Rack::Server</code>.</p><h3 id="cargando-rails-rack-lib-rack-server-rb"><a class="anchorlink" href="#cargando-rails-rack-lib-rack-server-rb"><span>2.4</span> Rack: lib/rack/server.rb</a></h3><p>La última vez que nos fuimos, el método <code>app</code> estaba siendo definido:</p><div class="interstitial code">
<pre><code class="highlight ruby"><span class="k">module</span> <span class="nn">Rack</span>
<span class="k">class</span> <span class="nc">Server</span>
<span class="k">def</span> <span class="nf">app</span>
<span class="vi">@app</span> <span class="o">||=</span> <span class="n">options</span><span class="p">[</span><span class="ss">:builder</span><span class="p">]</span> <span class="p">?</span> <span class="n">build_app_from_string</span> <span class="p">:</span> <span class="n">build_app_and_options_from_config</span>
<span class="k">end</span>
<span class="c1"># ...</span>
<span class="kp">private</span>
<span class="k">def</span> <span class="nf">build_app_and_options_from_config</span>