-
Notifications
You must be signed in to change notification settings - Fork 0
/
initialization.html
891 lines (805 loc) · 44.3 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>The Rails Initialization Process — 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/syntaxhighlighter/shCore.css" data-turbolinks-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" data-turbolinks-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" data-turbolinks-track="reload">
<link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<script src="javascripts/syntaxhighlighter.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="The Rails Initialization Process — Ruby on Rails Guides" />
<meta name="description" content="The Rails Initialization ProcessThis guide explains the internals of the initialization process in Rails. It is an extremely in-depth guide and recommended for advanced Rails developers.After reading this guide, you will know: How to use rails server. The timeline of Rails' initialization sequence. Where different files are required by the boot sequence. How the Rails::Server interface is defined and used." />
<meta property="og:description" content="The Rails Initialization ProcessThis guide explains the internals of the initialization process in Rails. It is an extremely in-depth guide and recommended for advanced Rails developers.After reading this guide, you will know: How to use rails server. The timeline of Rails' initialization sequence. Where different files are required by the boot sequence. How the Rails::Server interface is defined and used." />
<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 id="topNav">
<div class="wrapper">
<strong class="more-info-label">공식 웹사이트 <a href="https://rubyonrails.org/">rubyonrails.org:</a> </strong>
<span class="red-button more-info-button">
루비온레일스 웹사이트
</span>
<ul class="more-info-links s-hidden">
<li class="more-info"><a href="https://weblog.rubyonrails.org/">블로그</a></li>
<li class="more-info"><a href="https://guides.rubyonrails.org/">영문가이드</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">질문하기</a></li>
<li class="more-info"><a href="https://github.com/rails/rails">GitHub에서 기여하기</a></li>
</ul>
</div>
</div>
<div id="header">
<div class="wrapper clearfix">
<h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
<ul class="nav">
<li><a class="nav-item" href="index.html">홈</a></li>
<li class="guides-index guides-index-large">
<a href="index.html" id="guidesMenu" class="guides-index-item nav-item">가이드 인덱스</a>
<div id="guides" class="clearfix" style="display: none;">
<hr />
<div class="guides-section-container">
<div class="guides-section">
<dt>시작하면서</dt>
<dd><a href="getting_started.html">레일스로 시작하기</a></dd>
</div>
<div class="guides-section">
<dt>모델</dt>
<dd><a href="active_record_basics.html">액티브 레코드 기본</a></dd>
<dd><a href="active_record_migrations.html">액티브 레코드 마이그레이션</a></dd>
<dd><a href="active_record_validations.html">액티브 레코드 유효성 검증</a></dd>
<dd><a href="active_record_callbacks.html">액티브 레코드 콜백</a></dd>
<dd><a href="association_basics.html">Active Record Associations</a></dd>
<dd><a href="active_record_querying.html">Active Record Query Interface</a></dd>
</div>
<div class="guides-section">
<dt>Views</dt>
<dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd>
<dd><a href="form_helpers.html">Action View Form Helpers</a></dd>
</div>
<div class="guides-section">
<dt>Controllers</dt>
<dd><a href="action_controller_overview.html">Action Controller Overview</a></dd>
<dd><a href="routing.html">Rails Routing from the Outside In</a></dd>
</div>
<div class="guides-section">
<dt>Other Components</dt>
<dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd>
<dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd>
<dd><a href="active_job_basics.html">Active Job Basics</a></dd>
<dd><a href="active_storage_overview.html">Active Storage Overview</a></dd>
<dd><a href="action_cable_overview.html">Action Cable Overview</a></dd>
</div>
<div class="guides-section">
<dt>Digging Deeper</dt>
<dd><a href="i18n.html">Rails Internationalization (I18n) API</a></dd>
<dd><a href="testing.html">Testing Rails Applications</a></dd>
<dd><a href="security.html">Securing Rails Applications</a></dd>
<dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd>
<dd><a href="configuring.html">Configuring Rails Applications</a></dd>
<dd><a href="command_line.html">The Rails Command Line</a></dd>
<dd><a href="asset_pipeline.html">The Asset Pipeline</a></dd>
<dd><a href="working_with_javascript_in_rails.html">Working with JavaScript in Rails</a></dd>
<dd><a href="autoloading_and_reloading_constants.html">Autoloading and Reloading Constants (Zeitwerk Mode)</a></dd>
<dd><a href="autoloading_and_reloading_constants_classic_mode.html">Autoloading and Reloading Constants (Classic Mode)</a></dd>
<dd><a href="caching_with_rails.html">Caching with Rails: An Overview</a></dd>
<dd><a href="api_app.html">Using Rails for API-only Applications</a></dd>
</div>
<div class="guides-section">
<dt>Extending Rails</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>
<div class="guides-section">
<dt>Contributions</dt>
<dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
<dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
<dd><a href="ruby_on_rails_guides_guidelines.html">Guides Guidelines</a></dd>
</div>
<div class="guides-section">
<dt>Policies</dt>
<dd><a href="maintenance_policy.html">Maintenance Policy</a></dd>
</div>
<div class="guides-section">
<dt>Release Notes</dt>
<dd><a href="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</a></dd>
<dd><a href="6_0_release_notes.html">Version 6.0 - August 2019</a></dd>
<dd><a href="5_2_release_notes.html">Version 5.2 - April 2018</a></dd>
<dd><a href="5_1_release_notes.html">Version 5.1 - April 2017</a></dd>
<dd><a href="5_0_release_notes.html">Version 5.0 - June 2016</a></dd>
<dd><a href="4_2_release_notes.html">Version 4.2 - December 2014</a></dd>
<dd><a href="4_1_release_notes.html">Version 4.1 - April 2014</a></dd>
<dd><a href="4_0_release_notes.html">Version 4.0 - June 2013</a></dd>
<dd><a href="3_2_release_notes.html">Version 3.2 - January 2012</a></dd>
<dd><a href="3_1_release_notes.html">Version 3.1 - August 2011</a></dd>
<dd><a href="3_0_release_notes.html">Version 3.0 - August 2010</a></dd>
<dd><a href="2_3_release_notes.html">Version 2.3 - March 2009</a></dd>
<dd><a href="2_2_release_notes.html">Version 2.2 - November 2008</a></dd>
</div>
</div>
</div>
</li>
<li><a class="nav-item" href="contributing_to_ruby_on_rails.html">기여하기</a></li>
<li class="guides-index guides-index-small">
<select class="guides-index-item nav-item">
<option value="index.html">가이드 인덱스</option>
<optgroup label="시작하면서">
<option value="getting_started.html">레일스로 시작하기</option>
</optgroup>
<optgroup label="모델">
<option value="active_record_basics.html">액티브 레코드 기본</option>
<option value="active_record_migrations.html">액티브 레코드 마이그레이션</option>
<option value="active_record_validations.html">액티브 레코드 유효성 검증</option>
<option value="active_record_callbacks.html">액티브 레코드 콜백</option>
<option value="association_basics.html">Active Record Associations</option>
<option value="active_record_querying.html">Active Record Query Interface</option>
</optgroup>
<optgroup label="Views">
<option value="layouts_and_rendering.html">Layouts and Rendering in Rails</option>
<option value="form_helpers.html">Action View Form Helpers</option>
</optgroup>
<optgroup label="Controllers">
<option value="action_controller_overview.html">Action Controller Overview</option>
<option value="routing.html">Rails Routing from the Outside In</option>
</optgroup>
<optgroup label="Other Components">
<option value="active_support_core_extensions.html">Active Support Core Extensions</option>
<option value="action_mailer_basics.html">Action Mailer Basics</option>
<option value="active_job_basics.html">Active Job Basics</option>
<option value="active_storage_overview.html">Active Storage Overview</option>
<option value="action_cable_overview.html">Action Cable Overview</option>
</optgroup>
<optgroup label="Digging Deeper">
<option value="i18n.html">Rails Internationalization (I18n) API</option>
<option value="testing.html">Testing Rails Applications</option>
<option value="security.html">Securing Rails Applications</option>
<option value="debugging_rails_applications.html">Debugging Rails Applications</option>
<option value="configuring.html">Configuring Rails Applications</option>
<option value="command_line.html">The Rails Command Line</option>
<option value="asset_pipeline.html">The Asset Pipeline</option>
<option value="working_with_javascript_in_rails.html">Working with JavaScript in Rails</option>
<option value="autoloading_and_reloading_constants.html">Autoloading and Reloading Constants (Zeitwerk Mode)</option>
<option value="autoloading_and_reloading_constants_classic_mode.html">Autoloading and Reloading Constants (Classic Mode)</option>
<option value="caching_with_rails.html">Caching with Rails: An Overview</option>
<option value="api_app.html">Using Rails for API-only Applications</option>
</optgroup>
<optgroup label="Extending Rails">
<option value="rails_on_rack.html">Rails on Rack</option>
<option value="generators.html">Creating and Customizing Rails Generators & Templates</option>
</optgroup>
<optgroup label="Contributions">
<option value="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</option>
<option value="api_documentation_guidelines.html">API Documentation Guidelines</option>
<option value="ruby_on_rails_guides_guidelines.html">Guides Guidelines</option>
</optgroup>
<optgroup label="Policies">
<option value="maintenance_policy.html">Maintenance Policy</option>
</optgroup>
<optgroup label="Release Notes">
<option value="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</option>
<option value="6_0_release_notes.html">Version 6.0 - August 2019</option>
<option value="5_2_release_notes.html">Version 5.2 - April 2018</option>
<option value="5_1_release_notes.html">Version 5.1 - April 2017</option>
<option value="5_0_release_notes.html">Version 5.0 - June 2016</option>
<option value="4_2_release_notes.html">Version 4.2 - December 2014</option>
<option value="4_1_release_notes.html">Version 4.1 - April 2014</option>
<option value="4_0_release_notes.html">Version 4.0 - June 2013</option>
<option value="3_2_release_notes.html">Version 3.2 - January 2012</option>
<option value="3_1_release_notes.html">Version 3.1 - August 2011</option>
<option value="3_0_release_notes.html">Version 3.0 - August 2010</option>
<option value="2_3_release_notes.html">Version 2.3 - March 2009</option>
<option value="2_2_release_notes.html">Version 2.2 - November 2008</option>
</optgroup>
</select>
</li>
</ul>
</div>
</div>
<hr class="hide" />
<div id="feature">
<div class="wrapper">
<h2>The Rails Initialization Process</h2><p>This guide explains the internals of the initialization process in Rails.
It is an extremely in-depth guide and recommended for advanced Rails developers.</p><p>After reading this guide, you will know:</p>
<ul>
<li>How to use <code>rails server</code>.</li>
<li>The timeline of Rails' initialization sequence.</li>
<li>Where different files are required by the boot sequence.</li>
<li>How the Rails::Server interface is defined and used.</li>
</ul>
<div id="subCol">
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
<ol class="chapters">
<li>
<a href="#launch-bang">Launch!</a>
<ul>
<li><a href="#railties-exe-rails"><code>railties/exe/rails</code></a></li>
<li><a href="#railties-lib-rails-app-loader-rb"><code>railties/lib/rails/app_loader.rb</code></a></li>
<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="#launch-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="#loading-rails">Loading Rails</a>
<ul>
<li><a href="#railties-lib-rails-all-rb"><code>railties/lib/rails/all.rb</code></a></li>
<li><a href="#back-to-config-environment-rb">Back to <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="#loading-rails-rack-lib-rack-server-rb">Rack: lib/rack/server.rb</a></li>
</ul>
</li>
</ol>
</div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<p>This guide goes through every method call that is
required to boot up the Ruby on Rails stack for a default Rails
application, explaining each part in detail along the way. For this
guide, we will be focusing on what happens when you execute <code>rails server</code>
to boot your app.</p><div class="note"><p>Paths in this guide are relative to Rails or a Rails application unless otherwise specified.</p></div><div class="info"><p>If you want to follow along while browsing the Rails <a href="https://github.com/rails/rails">source
code</a>, we recommend that you use the <code>t</code>
key binding to open the file finder inside GitHub and find files
quickly.</p></div><h3 id="launch-bang"><a class="anchorlink" href="#launch-bang">1 Launch!</a></h3><p>Let's start to boot and initialize the app. A Rails application is usually
started by running <code>rails console</code> or <code>rails server</code>.</p><h4 id="railties-exe-rails"><a class="anchorlink" href="#railties-exe-rails">1.1 <code>railties/exe/rails</code></a></h4><p>The <code>rails</code> in the command <code>rails server</code> is a ruby executable in your load
path. This executable contains the following lines:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
version = ">= 0"
load Gem.bin_path('railties', 'rails', version)
</pre>
</div>
<p>If you try out this command in a Rails console, you would see that this loads
<code>railties/exe/rails</code>. A part of the file <code>railties/exe/rails</code> has the
following code:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require "rails/cli"
</pre>
</div>
<p>The file <code>railties/lib/rails/cli</code> in turn calls
<code>Rails::AppLoader.exec_app</code>.</p><h4 id="railties-lib-rails-app-loader-rb"><a class="anchorlink" href="#railties-lib-rails-app-loader-rb">1.2 <code>railties/lib/rails/app_loader.rb</code></a></h4><p>The primary goal of the function <code>exec_app</code> is to execute your app's
<code>bin/rails</code>. If the current directory does not have a <code>bin/rails</code>, it will
navigate upwards until it finds a <code>bin/rails</code> executable. Thus one can invoke a
<code>rails</code> command from anywhere inside a rails application.</p><p>For <code>rails server</code> the equivalent of the following command is executed:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ exec ruby bin/rails server
</pre>
</div>
<h4 id="bin-rails"><a class="anchorlink" href="#bin-rails">1.3 <code>bin/rails</code></a></h4><p>This file is as follows:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
#!/usr/bin/env ruby
APP_PATH = File.expand_path('../config/application', __dir__)
require_relative '../config/boot'
require 'rails/commands'
</pre>
</div>
<p>The <code>APP_PATH</code> constant will be used later in <code>rails/commands</code>. The <code>config/boot</code> file referenced here is the <code>config/boot.rb</code> file in our application which is responsible for loading Bundler and setting it up.</p><h4 id="config-boot-rb"><a class="anchorlink" href="#config-boot-rb">1.4 <code>config/boot.rb</code></a></h4><p><code>config/boot.rb</code> contains:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__)
require 'bundler/setup' # Set up gems listed in the Gemfile.
</pre>
</div>
<p>In a standard Rails application, there's a <code>Gemfile</code> which declares all
dependencies of the application. <code>config/boot.rb</code> sets
<code>ENV['BUNDLE_GEMFILE']</code> to the location of this file. If the <code>Gemfile</code>
exists, then <code>bundler/setup</code> is required. The require is used by Bundler to
configure the load path for your Gemfile's dependencies.</p><p>A standard Rails application depends on several gems, specifically:</p>
<ul>
<li>actioncable</li>
<li>actionmailer</li>
<li>actionpack</li>
<li>actionview</li>
<li>activejob</li>
<li>activemodel</li>
<li>activerecord</li>
<li>activestorage</li>
<li>activesupport</li>
<li>actionmailbox</li>
<li>actiontext</li>
<li>arel</li>
<li>builder</li>
<li>bundler</li>
<li>erubi</li>
<li>i18n</li>
<li>mail</li>
<li>mime-types</li>
<li>rack</li>
<li>rack-test</li>
<li>rails</li>
<li>railties</li>
<li>rake</li>
<li>sqlite3</li>
<li>thor</li>
<li>tzinfo</li>
</ul>
<h4 id="rails-commands-rb"><a class="anchorlink" href="#rails-commands-rb">1.5 <code>rails/commands.rb</code></a></h4><p>Once <code>config/boot.rb</code> has finished, the next file that is required is
<code>rails/commands</code>, which helps in expanding aliases. In the current case, the
<code>ARGV</code> array simply contains <code>server</code> which will be passed over:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require_relative "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
</pre>
</div>
<p>If we had used <code>s</code> rather than <code>server</code>, Rails would have used the <code>aliases</code>
defined here to find the matching command.</p><h4 id="rails-command-rb"><a class="anchorlink" href="#rails-command-rb">1.6 <code>rails/command.rb</code></a></h4><p>When one types a Rails command, <code>invoke</code> tries to lookup a command for the given
namespace and executes the command if found.</p><p>If Rails doesn't recognize the command, it hands the reins over to Rake
to run a task of the same name.</p><p>As shown, <code>Rails::Command</code> displays the help output automatically if the <code>args</code>
are empty.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module Rails::Command
class << self
def invoke(namespace, args = [], **config)
namespace = namespace.to_s
namespace = "help" if namespace.blank? || HELP_MAPPINGS.include?(namespace)
namespace = "version" if %w( -v --version ).include? namespace
if command = find_by_namespace(namespace)
command.perform(namespace, args, config)
else
find_by_namespace("rake").perform(namespace, args, config)
end
end
end
end
</pre>
</div>
<p>With the <code>server</code> command, Rails will further run the following code:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module Rails
module Command
class ServerCommand < Base # :nodoc:
def perform
set_application_directory!
Rails::Server.new.tap do |server|
# Require application after server sets environment to propagate
# the --environment option.
require APP_PATH
Dir.chdir(Rails.application.root)
server.start
end
end
end
end
end
</pre>
</div>
<p>This file will change into the Rails root directory (a path two directories up
from <code>APP_PATH</code> which points at <code>config/application.rb</code>), but only if the
<code>config.ru</code> file isn't found. This then starts up the <code>Rails::Server</code> class.</p><h4 id="actionpack-lib-action-dispatch-rb"><a class="anchorlink" href="#actionpack-lib-action-dispatch-rb">1.7 <code>actionpack/lib/action_dispatch.rb</code></a></h4><p>Action Dispatch is the routing component of the Rails framework.
It adds functionality like routing, session, and common middlewares.</p><h4 id="rails-commands-server-server-command-rb"><a class="anchorlink" href="#rails-commands-server-server-command-rb">1.8 <code>rails/commands/server/server_command.rb</code></a></h4><p>The <code>Rails::Server</code> class is defined in this file by inheriting from
<code>Rack::Server</code>. When <code>Rails::Server.new</code> is called, this calls the <code>initialize</code>
method in <code>rails/commands/server/server_command.rb</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def initialize(*)
super
set_environment
end
</pre>
</div>
<p>Firstly, <code>super</code> is called which calls the <code>initialize</code> method on <code>Rack::Server</code>.</p><h4 id="launch-bang-rack-lib-rack-server-rb"><a class="anchorlink" href="#launch-bang-rack-lib-rack-server-rb">1.9 Rack: <code>lib/rack/server.rb</code></a></h4><p><code>Rack::Server</code> is responsible for providing a common server interface for all Rack-based applications, which Rails is now a part of.</p><p>The <code>initialize</code> method in <code>Rack::Server</code> simply sets a couple of variables:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def initialize(options = nil)
@options = options
@app = options[:app] if options && options[:app]
end
</pre>
</div>
<p>In this case, <code>options</code> will be <code>nil</code> so nothing happens in this method.</p><p>After <code>super</code> has finished in <code>Rack::Server</code>, we jump back to
<code>rails/commands/server/server_command.rb</code>. At this point, <code>set_environment</code>
is called within the context of the <code>Rails::Server</code> object and this method
doesn't appear to do much at first glance:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def set_environment
ENV["RAILS_ENV"] ||= options[:environment]
end
</pre>
</div>
<p>In fact, the <code>options</code> method here does quite a lot. This method is defined in <code>Rack::Server</code> like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def options
@options ||= parse_options(ARGV)
end
</pre>
</div>
<p>Then <code>parse_options</code> is defined like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def parse_options(args)
options = default_options
# Don't evaluate CGI ISINDEX parameters.
# http://www.meb.uni-bonn.de/docs/cgi/cl.html
args.clear if ENV.include?("REQUEST_METHOD")
options.merge! opt_parser.parse!(args)
options[:config] = ::File.expand_path(options[:config])
ENV["RACK_ENV"] = options[:environment]
options
end
</pre>
</div>
<p>With the <code>default_options</code> set to this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def default_options
super.merge(
Port: ENV.fetch("PORT", 3000).to_i,
Host: ENV.fetch("HOST", "localhost").dup,
DoNotReverseLookup: true,
environment: (ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development").dup,
daemonize: false,
caching: nil,
pid: Options::DEFAULT_PID_PATH,
restart_cmd: restart_command)
end
</pre>
</div>
<p>There is no <code>REQUEST_METHOD</code> key in <code>ENV</code> so we can skip over that line. The next line merges in the options from <code>opt_parser</code> which is defined plainly in <code>Rack::Server</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def opt_parser
Options.new
end
</pre>
</div>
<p>The class <strong>is</strong> defined in <code>Rack::Server</code>, but is overwritten in
<code>Rails::Server</code> to take different arguments. Its <code>parse!</code> method looks
like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def parse!(args)
args, options = args.dup, {}
option_parser(options).parse! args
options[:log_stdout] = options[:daemonize].blank? && (options[:environment] || Rails.env) == "development"
options[:server] = args.shift
options
end
</pre>
</div>
<p>This method will set up keys for the <code>options</code> which Rails will then be
able to use to determine how its server should run. After <code>initialize</code>
has finished, we jump back into the server command where <code>APP_PATH</code> (which was
set earlier) is required.</p><h4 id="config-application"><a class="anchorlink" href="#config-application">1.10 <code>config/application</code></a></h4><p>When <code>require APP_PATH</code> is executed, <code>config/application.rb</code> is loaded (recall
that <code>APP_PATH</code> is defined in <code>bin/rails</code>). This file exists in your application
and it's free for you to change based on your needs.</p><h4 id="rails-server-start"><a class="anchorlink" href="#rails-server-start">1.11 <code>Rails::Server#start</code></a></h4><p>After <code>config/application</code> is loaded, <code>server.start</code> is called. This method is
defined like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def start
print_boot_information
trap(:INT) { exit }
create_tmp_directories
setup_dev_caching
log_to_stdout if options[:log_stdout]
super
...
end
private
def print_boot_information
...
puts "=> Run `rails server -h` for more startup options"
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 setup_dev_caching
if options[:environment] == "development"
Rails::DevCaching.enable_by_argument(options[:caching])
end
end
def log_to_stdout
wrapped_app # touch the app so the logger is set up
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
</pre>
</div>
<p>This is where the first output of the Rails initialization happens. This method
creates a trap for <code>INT</code> signals, so if you <code>CTRL-C</code> the server, it will exit the
process. As we can see from the code here, it will create the <code>tmp/cache</code>,
<code>tmp/pids</code>, and <code>tmp/sockets</code> directories. It then enables caching in development
if <code>rails server</code> is called with <code>--dev-caching</code>. Finally, it calls <code>wrapped_app</code> which is
responsible for creating the Rack app, before creating and assigning an instance
of <code>ActiveSupport::Logger</code>.</p><p>The <code>super</code> method will call <code>Rack::Server.start</code> which begins its definition like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
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]
# Touch the wrapped app, so that the config.ru is loaded before
# daemonization (i.e. before chdir, etc).
wrapped_app
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
</pre>
</div>
<p>The interesting part for a Rails app is the last line, <code>server.run</code>. Here we encounter the <code>wrapped_app</code> method again, which this time
we're going to explore more (even though it was executed before, and
thus memoized by now).</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
@wrapped_app ||= build_app app
</pre>
</div>
<p>The <code>app</code> method here is defined like so:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
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)
self.options.merge! options
app
end
def build_app_from_string
Rack::Builder.new_from_string(self.options[:builder])
end
</pre>
</div>
<p>The <code>options[:config]</code> value defaults to <code>config.ru</code> which contains this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# This file is used by Rack-based servers to start the application.
require_relative 'config/environment'
run <%= app_const %>
</pre>
</div>
<p>The <code>Rack::Builder.parse_file</code> method here takes the content from this <code>config.ru</code> file and parses it using this code:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
app = new_from_string cfgfile, config
...
def self.new_from_string(builder_script, file="(rackup)")
eval "Rack::Builder.new {\n" + builder_script + "\n}.to_app",
TOPLEVEL_BINDING, file, 0
end
</pre>
</div>
<p>The <code>initialize</code> method of <code>Rack::Builder</code> will take the block here and execute it within an instance of <code>Rack::Builder</code>. This is where the majority of the initialization process of Rails happens. The <code>require</code> line for <code>config/environment.rb</code> in <code>config.ru</code> is the first to run:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require_relative 'config/environment'
</pre>
</div>
<h4 id="config-environment-rb"><a class="anchorlink" href="#config-environment-rb">1.12 <code>config/environment.rb</code></a></h4><p>This file is the common file required by <code>config.ru</code> (<code>rails server</code>) and Passenger. This is where these two ways to run the server meet; everything before this point has been Rack and Rails setup.</p><p>This file begins with requiring <code>config/application.rb</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require_relative 'application'
</pre>
</div>
<h4 id="config-application-rb"><a class="anchorlink" href="#config-application-rb">1.13 <code>config/application.rb</code></a></h4><p>This file requires <code>config/boot.rb</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require_relative 'boot'
</pre>
</div>
<p>But only if it hasn't been required before, which would be the case in <code>rails server</code>
but <strong>wouldn't</strong> be the case with Passenger.</p><p>Then the fun begins!</p><h3 id="loading-rails"><a class="anchorlink" href="#loading-rails">2 Loading Rails</a></h3><p>The next line in <code>config/application.rb</code> is:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require 'rails/all'
</pre>
</div>
<h4 id="railties-lib-rails-all-rb"><a class="anchorlink" href="#railties-lib-rails-all-rb">2.1 <code>railties/lib/rails/all.rb</code></a></h4><p>This file is responsible for requiring all the individual frameworks of Rails:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
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
sprockets/railtie
).each do |railtie|
begin
require railtie
rescue LoadError
end
end
</pre>
</div>
<p>This is where all the Rails frameworks are loaded and thus made
available to the application. We won't go into detail of what happens
inside each of those frameworks, but you're encouraged to try and
explore them on your own.</p><p>For now, just keep in mind that common functionality like Rails engines,
I18n and Rails configuration are all being defined here.</p><h4 id="back-to-config-environment-rb"><a class="anchorlink" href="#back-to-config-environment-rb">2.2 Back to <code>config/environment.rb</code></a></h4><p>The rest of <code>config/application.rb</code> defines the configuration for the
<code>Rails::Application</code> which will be used once the application is fully
initialized. When <code>config/application.rb</code> has finished loading Rails and defined
the application namespace, we go back to <code>config/environment.rb</code>. Here, the
application is initialized with <code>Rails.application.initialize!</code>, which is
defined in <code>rails/application.rb</code>.</p><h4 id="railties-lib-rails-application-rb"><a class="anchorlink" href="#railties-lib-rails-application-rb">2.3 <code>railties/lib/rails/application.rb</code></a></h4><p>The <code>initialize!</code> method looks like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def initialize!(group=:default) #:nodoc:
raise "Application has been already initialized." if @initialized
run_initializers(group, self)
@initialized = true
self
end
</pre>
</div>
<p>As you can see, you can only initialize an app once. The initializers are run through
the <code>run_initializers</code> method which is defined in <code>railties/lib/rails/initializable.rb</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
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
</pre>
</div>
<p>The <code>run_initializers</code> code itself is tricky. What Rails is doing here is
traversing all the class ancestors looking for those that respond to an
<code>initializers</code> method. It then sorts the ancestors by name, and runs them.
For example, the <code>Engine</code> class will make all the engines available by
providing an <code>initializers</code> method on them.</p><p>The <code>Rails::Application</code> class, as defined in <code>railties/lib/rails/application.rb</code>
defines <code>bootstrap</code>, <code>railtie</code>, and <code>finisher</code> initializers. The <code>bootstrap</code> initializers
prepare the application (like initializing the logger) while the <code>finisher</code>
initializers (like building the middleware stack) are run last. The <code>railtie</code>
initializers are the initializers which have been defined on the <code>Rails::Application</code>
itself and are run between the <code>bootstrap</code> and <code>finishers</code>.</p><p>After this is done we go back to <code>Rack::Server</code>.</p><h4 id="loading-rails-rack-lib-rack-server-rb"><a class="anchorlink" href="#loading-rails-rack-lib-rack-server-rb">2.4 Rack: lib/rack/server.rb</a></h4><p>Last time we left when the <code>app</code> method was being defined:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
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)
self.options.merge! options
app
end
def build_app_from_string
Rack::Builder.new_from_string(self.options[:builder])
end
</pre>
</div>
<p>At this point <code>app</code> is the Rails app itself (a middleware), and what
happens next is Rack will call all the provided middlewares:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def build_app(app)
middleware[options[:environment]].reverse_each do |middleware|
middleware = middleware.call(self) if middleware.respond_to?(:call)
next unless middleware
klass = middleware.shift
app = klass.new(app, *middleware)
end
app
end
</pre>
</div>
<p>Remember, <code>build_app</code> was called (by <code>wrapped_app</code>) in the last line of <code>Server#start</code>.
Here's how it looked like when we left:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
server.run wrapped_app, options, &blk
</pre>
</div>
<p>At this point, the implementation of <code>server.run</code> will depend on the
server you're using. For example, if you were using Puma, here's what
the <code>run</code> method would look like:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
...
DEFAULT_OPTIONS = {
:Host => '0.0.0.0',
:Port => 8080,
:Threads => '0:16',
:Verbose => false
}
def self.run(app, options = {})
options = DEFAULT_OPTIONS.merge(options)
if options[:Verbose]
app = Rack::CommonLogger.new(app, STDOUT)
end
if options[:environment]
ENV['RACK_ENV'] = options[:environment].to_s
end
server = ::Puma::Server.new(app)
min, max = options[:Threads].split(':', 2)
puts "Puma #{::Puma::Const::PUMA_VERSION} starting..."
puts "* Min threads: #{min}, max threads: #{max}"
puts "* Environment: #{ENV['RACK_ENV']}"
puts "* Listening on tcp://#{options[:Host]}:#{options[:Port]}"
server.add_tcp_listener options[:Host], options[:Port]
server.min_threads = min
server.max_threads = max
yield server if block_given?
begin
server.run.join
rescue Interrupt
puts "* Gracefully stopping, waiting for requests to finish"
server.stop(true)
puts "* Goodbye!"
end
end
</pre>
</div>
<p>We won't dig into the server configuration itself, but this is
the last piece of our journey in the Rails initialization process.</p><p>This high level overview will help you understand when your code is
executed and how, and overall become a better Rails developer. If you
still want to know more, the Rails source code itself is probably the
best place to go next.</p>
<h3>피드백</h3>
<p>
이 가이드의 품질을 향상시키기 위해 여러분의 도움이 필요하다.
</p>
<p>
오타나 실제 오류를 발견시 여러분의 기여를 권고한다. 시작하려면 본 <a href="https://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html#contributing-to-the-rails-documentation">가이드의 기여</a> 섹션을 읽어보기 바란다.
</p>
<p>
미완성된 컨텐츠나 업데이트되지 않은 내용을 발견할 수도 있다. 누락된 문서는 master 브랜치에 추가한다. 제시된 이슈들이 master 브랜치 상에서 이미 해결되었는지 여부를 확인하려면 먼저 <a href="https://edgeguides.rubyonrails.org">Edge Guides</a>를 확인한다. 스타일과 규칙에 대해서는 <a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a>을 확인한다.
</p>
<p>
어떤 이유로든 고칠 수 있지만 직접 패치 할 수 없는 경우 <a href="https://github.com/rails/rails/issues">이슈를 새로 오픈</a>하면 된다.
</p>
<p>
그리고 마지막으로, 루비온레일스 문서에 관한 모든 논의는 <a href="https://groups.google.com/forum/#!forum/rubyonrails-docs">rubyonrails-docs 메일링 리스트</a> 상에서 언제든지 가능하다.
</p>
</div>
</div>
</div>
<hr class="hide" />
<div id="footer">
<div class="wrapper">
<p>본 결과물은 <a href="https://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International License</a> 를 준수한다. </p>
<p>"Rails", "Ruby on Rails", 그리고 레일스 로고는 David Heinemeier Hansson의 등록상표이다. 판권 소유.</p>
</div>
</div>
</body>
</html>