-
Notifications
You must be signed in to change notification settings - Fork 0
/
asset_pipeline.html
1231 lines (1150 loc) · 78.2 KB
/
asset_pipeline.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>The Asset Pipeline — 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 Asset Pipeline — Ruby on Rails Guides" />
<meta name="description" content="The Asset PipelineThis guide covers the asset pipeline.After reading this guide, you will know: What the asset pipeline is and what it does. How to properly organize your application assets. The benefits of the asset pipeline. How to add a pre-processor to the pipeline. How to package assets with a gem." />
<meta property="og:description" content="The Asset PipelineThis guide covers the asset pipeline.After reading this guide, you will know: What the asset pipeline is and what it does. How to properly organize your application assets. The benefits of the asset pipeline. How to add a pre-processor to the pipeline. How to package assets with a gem." />
<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 Asset Pipeline</h2><p>This guide covers the asset pipeline.</p><p>After reading this guide, you will know:</p>
<ul>
<li>What the asset pipeline is and what it does.</li>
<li>How to properly organize your application assets.</li>
<li>The benefits of the asset pipeline.</li>
<li>How to add a pre-processor to the pipeline.</li>
<li>How to package assets with a gem.</li>
</ul>
<div id="subCol">
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
<ol class="chapters">
<li>
<a href="#what-is-the-asset-pipeline-questionmark">What is the Asset Pipeline?</a>
<ul>
<li><a href="#main-features">Main Features</a></li>
<li><a href="#what-is-fingerprinting-and-why-should-i-care-questionmark">What is Fingerprinting and Why Should I Care?</a></li>
</ul>
</li>
<li>
<a href="#how-to-use-the-asset-pipeline">How to Use the Asset Pipeline</a>
<ul>
<li><a href="#controller-specific-assets">Controller Specific Assets</a></li>
<li><a href="#asset-organization">Asset Organization</a></li>
<li><a href="#coding-links-to-assets">Coding Links to Assets</a></li>
<li><a href="#manifest-files-and-directives">Manifest Files and Directives</a></li>
<li><a href="#preprocessing">Preprocessing</a></li>
</ul>
</li>
<li>
<a href="#in-development">In Development</a>
<ul>
<li><a href="#raise-an-error-when-an-asset-is-not-found">Raise an Error When an Asset is Not Found</a></li>
<li><a href="#turning-digests-off">Turning Digests Off</a></li>
<li><a href="#turning-debugging-off">Turning Debugging Off</a></li>
</ul>
</li>
<li>
<a href="#in-production">In Production</a>
<ul>
<li><a href="#precompiling-assets">Precompiling Assets</a></li>
<li><a href="#local-precompilation">Local Precompilation</a></li>
<li><a href="#live-compilation">Live Compilation</a></li>
<li><a href="#cdns">CDNs</a></li>
</ul>
</li>
<li>
<a href="#customizing-the-pipeline">Customizing the Pipeline</a>
<ul>
<li><a href="#css-compression">CSS Compression</a></li>
<li><a href="#javascript-compression">JavaScript Compression</a></li>
<li><a href="#gzipping-your-assets">GZipping your assets</a></li>
<li><a href="#using-your-own-compressor">Using Your Own Compressor</a></li>
<li><a href="#changing-the-assets-path">Changing the <em>assets</em> Path</a></li>
<li><a href="#x-sendfile-headers">X-Sendfile Headers</a></li>
</ul>
</li>
<li><a href="#assets-cache-store">Assets Cache Store</a></li>
<li><a href="#adding-assets-to-your-gems">Adding Assets to Your Gems</a></li>
<li><a href="#making-your-library-or-gem-a-pre-processor">Making Your Library or Gem a Pre-Processor</a></li>
</ol>
</div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<h3 id="what-is-the-asset-pipeline-questionmark"><a class="anchorlink" href="#what-is-the-asset-pipeline-questionmark">1 What is the Asset Pipeline?</a></h3><p>The asset pipeline provides a framework to concatenate and minify or compress
JavaScript and CSS assets. It also adds the ability to write these assets in
other languages and pre-processors such as CoffeeScript, Sass, and ERB.
It allows assets in your application to be automatically combined with assets
from other gems.</p><p>The asset pipeline is implemented by the
<a href="https://github.com/rails/sprockets-rails">sprockets-rails</a> gem,
and is enabled by default. You can disable it while creating a new application by
passing the <code>--skip-sprockets</code> option.</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
rails new appname --skip-sprockets
</pre>
</div>
<p>Rails automatically adds the <code>sass-rails</code> gem to your <code>Gemfile</code>, which is used
by Sprockets for asset compression:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
gem 'sass-rails'
</pre>
</div>
<p>Using the <code>--skip-sprockets</code> option will prevent Rails from adding
them to your <code>Gemfile</code>, so if you later want to enable
the asset pipeline you will have to add those gems to your <code>Gemfile</code>. Also,
creating an application with the <code>--skip-sprockets</code> option will generate
a slightly different <code>config/application.rb</code> file, with a require statement
for the sprockets railtie that is commented-out. You will have to remove
the comment operator on that line to later enable the asset pipeline:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# require "sprockets/railtie"
</pre>
</div>
<p>To set asset compression methods, set the appropriate configuration options
in <code>production.rb</code> - <code>config.assets.css_compressor</code> for your CSS and
<code>config.assets.js_compressor</code> for your JavaScript:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.assets.css_compressor = :yui
config.assets.js_compressor = :uglifier
</pre>
</div>
<div class="note"><p>The <code>sass-rails</code> gem is automatically used for CSS compression if included
in the <code>Gemfile</code> and no <code>config.assets.css_compressor</code> option is set.</p></div><h4 id="main-features"><a class="anchorlink" href="#main-features">1.1 Main Features</a></h4><p>The first feature of the pipeline is to concatenate assets, which can reduce the
number of requests that a browser makes to render a web page. Web browsers are
limited in the number of requests that they can make in parallel, so fewer
requests can mean faster loading for your application.</p><p>Sprockets concatenates all JavaScript files into one master <code>.js</code> file and all
CSS files into one master <code>.css</code> file. As you'll learn later in this guide, you
can customize this strategy to group files any way you like. In production,
Rails inserts an SHA256 fingerprint into each filename so that the file is
cached by the web browser. You can invalidate the cache by altering this
fingerprint, which happens automatically whenever you change the file contents.</p><p>The second feature of the asset pipeline is asset minification or compression.
For CSS files, this is done by removing whitespace and comments. For JavaScript,
more complex processes can be applied. You can choose from a set of built in
options or specify your own.</p><p>The third feature of the asset pipeline is it allows coding assets via a
higher-level language, with precompilation down to the actual assets. Supported
languages include Sass for CSS, CoffeeScript for JavaScript, and ERB for both by
default.</p><h4 id="what-is-fingerprinting-and-why-should-i-care-questionmark"><a class="anchorlink" href="#what-is-fingerprinting-and-why-should-i-care-questionmark">1.2 What is Fingerprinting and Why Should I Care?</a></h4><p>Fingerprinting is a technique that makes the name of a file dependent on the
contents of the file. When the file contents change, the filename is also
changed. For content that is static or infrequently changed, this provides an
easy way to tell whether two versions of a file are identical, even across
different servers or deployment dates.</p><p>When a filename is unique and based on its content, HTTP headers can be set to
encourage caches everywhere (whether at CDNs, at ISPs, in networking equipment,
or in web browsers) to keep their own copy of the content. When the content is
updated, the fingerprint will change. This will cause the remote clients to
request a new copy of the content. This is generally known as <em>cache busting</em>.</p><p>The technique Sprockets uses for fingerprinting is to insert a hash of the
content into the name, usually at the end. For example a CSS file <code>global.css</code></p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
global-908e25f4bf641868d8683022a5b62f54.css
</pre>
</div>
<p>This is the strategy adopted by the Rails asset pipeline.</p><p>Rails' old strategy was to append a date-based query string to every asset linked
with a built-in helper. In the source the generated code looked like this:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
/stylesheets/global.css?1309495796
</pre>
</div>
<p>The query string strategy has several disadvantages:</p>
<ol>
<li>
<p><strong>Not all caches will reliably cache content where the filename only differs by
query parameters</strong></p>
<p><a href="https://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/">Steve Souders recommends</a>,
"...avoiding a querystring for cacheable resources". He found that in this
case 5-20% of requests will not be cached. Query strings in particular do not
work at all with some CDNs for cache invalidation.</p>
</li>
<li>
<p><strong>The file name can change between nodes in multi-server environments.</strong></p>
<p>The default query string in Rails 2.x is based on the modification time of
the files. When assets are deployed to a cluster, there is no guarantee that the
timestamps will be the same, resulting in different values being used depending
on which server handles the request.</p>
</li>
<li>
<p><strong>Too much cache invalidation</strong></p>
<p>When static assets are deployed with each new release of code, the mtime
(time of last modification) of <em>all</em> these files changes, forcing all remote
clients to fetch them again, even when the content of those assets has not changed.</p>
</li>
</ol>
<p>Fingerprinting fixes these problems by avoiding query strings, and by ensuring
that filenames are consistent based on their content.</p><p>Fingerprinting is enabled by default for both the development and production
environments. You can enable or disable it in your configuration through the
<code>config.assets.digest</code> option.</p><p>More reading:</p>
<ul>
<li><a href="https://developers.google.com/speed/docs/insights/LeverageBrowserCaching">Optimize caching</a></li>
<li><a href="http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/">Revving Filenames: don't use querystring</a></li>
</ul>
<h3 id="how-to-use-the-asset-pipeline"><a class="anchorlink" href="#how-to-use-the-asset-pipeline">2 How to Use the Asset Pipeline</a></h3><p>In previous versions of Rails, all assets were located in subdirectories of
<code>public</code> such as <code>images</code>, <code>javascripts</code> and <code>stylesheets</code>. With the asset
pipeline, the preferred location for these assets is now the <code>app/assets</code>
directory. Files in this directory are served by the Sprockets middleware.</p><p>Assets can still be placed in the <code>public</code> hierarchy. Any assets under <code>public</code>
will be served as static files by the application or web server when
<code>config.public_file_server.enabled</code> is set to true. You should use <code>app/assets</code> for
files that must undergo some pre-processing before they are served.</p><p>In production, Rails precompiles these files to <code>public/assets</code> by default. The
precompiled copies are then served as static assets by the web server. The files
in <code>app/assets</code> are never served directly in production.</p><h4 id="controller-specific-assets"><a class="anchorlink" href="#controller-specific-assets">2.1 Controller Specific Assets</a></h4><p>When you generate a scaffold or a controller, Rails also generates a
Cascading Style Sheet file (or SCSS file if <code>sass-rails</code> is in the <code>Gemfile</code>)
for that controller. Additionally, when generating a scaffold, Rails generates
the file <code>scaffolds.css</code> (or <code>scaffolds.scss</code> if <code>sass-rails</code> is in the
<code>Gemfile</code>.)</p><p>For example, if you generate a <code>ProjectsController</code>, Rails will also add a new
file at <code>app/assets/stylesheets/projects.scss</code>. By default these files will be
ready to use by your application immediately using the <code>require_tree</code> directive. See
<a href="#manifest-files-and-directives">Manifest Files and Directives</a> for more details
on require_tree.</p><p>You can also opt to include controller specific stylesheets and JavaScript files
only in their respective controllers using the following:</p><p><code><%= javascript_include_tag params[:controller] %></code> or <code><%= stylesheet_link_tag
params[:controller] %></code></p><p>When doing this, ensure you are not using the <code>require_tree</code> directive, as that
will result in your assets being included more than once.</p><div class="warning"><p>When using asset precompilation, you will need to ensure that your
controller assets will be precompiled when loading them on a per page basis. By
default <code>.coffee</code> and <code>.scss</code> files will not be precompiled on their own. See
<a href="#precompiling-assets">Precompiling Assets</a> for more information on how
precompiling works.</p></div><div class="note"><p>You must have an ExecJS supported runtime in order to use CoffeeScript.
If you are using macOS or Windows, you have a JavaScript runtime installed in
your operating system. Check <a href="https://github.com/rails/execjs#readme">ExecJS</a> documentation to know all supported JavaScript runtimes.</p></div><p>You can also disable generation of controller specific asset files by adding the
following to your <code>config/application.rb</code> configuration:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.generators do |g|
g.assets false
end
</pre>
</div>
<h4 id="asset-organization"><a class="anchorlink" href="#asset-organization">2.2 Asset Organization</a></h4><p>Pipeline assets can be placed inside an application in one of three locations:
<code>app/assets</code>, <code>lib/assets</code> or <code>vendor/assets</code>.</p>
<ul>
<li><p><code>app/assets</code> is for assets that are owned by the application, such as custom
images, JavaScript files, or stylesheets.</p></li>
<li><p><code>lib/assets</code> is for your own libraries' code that doesn't really fit into the
scope of the application or those libraries which are shared across applications.</p></li>
<li><p><code>vendor/assets</code> is for assets that are owned by outside entities, such as
code for JavaScript plugins and CSS frameworks. Keep in mind that third party
code with references to other files also processed by the asset Pipeline (images,
stylesheets, etc.), will need to be rewritten to use helpers like <code>asset_path</code>.</p></li>
</ul>
<h5 id="search-paths"><a class="anchorlink" href="#search-paths">2.2.1 Search Paths</a></h5><p>When a file is referenced from a manifest or a helper, Sprockets searches the
three default asset locations for it.</p><p>The default locations are: the <code>images</code>, <code>javascripts</code> and <code>stylesheets</code>
directories under the <code>app/assets</code> folder, but these subdirectories
are not special - any path under <code>assets/*</code> will be searched.</p><p>For example, these files:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
app/assets/javascripts/home.js
lib/assets/javascripts/moovinator.js
vendor/assets/javascripts/slider.js
vendor/assets/somepackage/phonebox.js
</pre>
</div>
<p>would be referenced in a manifest like this:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
//= require home
//= require moovinator
//= require slider
//= require phonebox
</pre>
</div>
<p>Assets inside subdirectories can also be accessed.</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
app/assets/javascripts/sub/something.js
</pre>
</div>
<p>is referenced as:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
//= require sub/something
</pre>
</div>
<p>You can view the search path by inspecting
<code>Rails.application.config.assets.paths</code> in the Rails console.</p><p>Besides the standard <code>assets/*</code> paths, additional (fully qualified) paths can be
added to the pipeline in <code>config/initializers/assets.rb</code>. For example:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Rails.application.config.assets.paths << Rails.root.join("lib", "videoplayer", "flash")
</pre>
</div>
<p>Paths are traversed in the order they occur in the search path. By default,
this means the files in <code>app/assets</code> take precedence, and will mask
corresponding paths in <code>lib</code> and <code>vendor</code>.</p><p>It is important to note that files you want to reference outside a manifest must
be added to the precompile array or they will not be available in the production
environment.</p><h5 id="using-index-files"><a class="anchorlink" href="#using-index-files">2.2.2 Using Index Files</a></h5><p>Sprockets uses files named <code>index</code> (with the relevant extensions) for a special
purpose.</p><p>For example, if you have a jQuery library with many modules, which is stored in
<code>lib/assets/javascripts/library_name</code>, the file <code>lib/assets/javascripts/library_name/index.js</code> serves as
the manifest for all files in this library. This file could include a list of
all the required files in order, or a simple <code>require_tree</code> directive.</p><p>The library as a whole can be accessed in the application manifest like so:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
//= require library_name
</pre>
</div>
<p>This simplifies maintenance and keeps things clean by allowing related code to
be grouped before inclusion elsewhere.</p><h4 id="coding-links-to-assets"><a class="anchorlink" href="#coding-links-to-assets">2.3 Coding Links to Assets</a></h4><p>Sprockets does not add any new methods to access your assets - you still use the
familiar <code>javascript_include_tag</code> and <code>stylesheet_link_tag</code>:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= stylesheet_link_tag "application", media: "all" %>
<%= javascript_include_tag "application" %>
</pre>
</div>
<p>If using the turbolinks gem, which is included by default in Rails, then
include the 'data-turbolinks-track' option which causes turbolinks to check if
an asset has been updated and if so loads it into the page:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => "reload" %>
<%= javascript_include_tag "application", "data-turbolinks-track" => "reload" %>
</pre>
</div>
<p>In regular views you can access images in the <code>app/assets/images</code> directory
like this:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= image_tag "rails.png" %>
</pre>
</div>
<p>Provided that the pipeline is enabled within your application (and not disabled
in the current environment context), this file is served by Sprockets. If a file
exists at <code>public/assets/rails.png</code> it is served by the web server.</p><p>Alternatively, a request for a file with an SHA256 hash such as
<code>public/assets/rails-f90d8a84c707a8dc923fca1ca1895ae8ed0a09237f6992015fef1e11be77c023.png</code>
is treated the same way. How these hashes are generated is covered in the <a href="#in-production">In
Production</a> section later on in this guide.</p><p>Sprockets will also look through the paths specified in <code>config.assets.paths</code>,
which includes the standard application paths and any paths added by Rails
engines.</p><p>Images can also be organized into subdirectories if required, and then can be
accessed by specifying the directory's name in the tag:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= image_tag "icons/rails.png" %>
</pre>
</div>
<div class="warning"><p>If you're precompiling your assets (see <a href="#in-production">In Production</a>
below), linking to an asset that does not exist will raise an exception in the
calling page. This includes linking to a blank string. As such, be careful using
<code>image_tag</code> and the other helpers with user-supplied data.</p></div><h5 id="css-and-erb"><a class="anchorlink" href="#css-and-erb">2.3.1 CSS and ERB</a></h5><p>The asset pipeline automatically evaluates ERB. This means if you add an
<code>erb</code> extension to a CSS asset (for example, <code>application.css.erb</code>), then
helpers like <code>asset_path</code> are available in your CSS rules:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
.class { background-image: url(<%= asset_path 'image.png' %>) }
</pre>
</div>
<p>This writes the path to the particular asset being referenced. In this example,
it would make sense to have an image in one of the asset load paths, such as
<code>app/assets/images/image.png</code>, which would be referenced here. If this image is
already available in <code>public/assets</code> as a fingerprinted file, then that path is
referenced.</p><p>If you want to use a <a href="https://en.wikipedia.org/wiki/Data_URI_scheme">data URI</a> -
a method of embedding the image data directly into the CSS file - you can use
the <code>asset_data_uri</code> helper.</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
#logo { background: url(<%= asset_data_uri 'logo.png' %>) }
</pre>
</div>
<p>This inserts a correctly-formatted data URI into the CSS source.</p><p>Note that the closing tag cannot be of the style <code>-%></code>.</p><h5 id="css-and-sass"><a class="anchorlink" href="#css-and-sass">2.3.2 CSS and Sass</a></h5><p>When using the asset pipeline, paths to assets must be re-written and
<code>sass-rails</code> provides <code>-url</code> and <code>-path</code> helpers (hyphenated in Sass,
underscored in Ruby) for the following asset classes: image, font, video, audio,
JavaScript and stylesheet.</p>
<ul>
<li>
<code>image-url("rails.png")</code> returns <code>url(/assets/rails.png)</code>
</li>
<li>
<code>image-path("rails.png")</code> returns <code>"/assets/rails.png"</code>
</li>
</ul>
<p>The more generic form can also be used:</p>
<ul>
<li>
<code>asset-url("rails.png")</code> returns <code>url(/assets/rails.png)</code>
</li>
<li>
<code>asset-path("rails.png")</code> returns <code>"/assets/rails.png"</code>
</li>
</ul>
<h5 id="javascript-coffeescript-and-erb"><a class="anchorlink" href="#javascript-coffeescript-and-erb">2.3.3 JavaScript/CoffeeScript and ERB</a></h5><p>If you add an <code>erb</code> extension to a JavaScript asset, making it something such as
<code>application.js.erb</code>, you can then use the <code>asset_path</code> helper in your
JavaScript code:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$('#logo').attr({ src: "<%= asset_path('logo.png') %>" });
</pre>
</div>
<p>This writes the path to the particular asset being referenced.</p><p>Similarly, you can use the <code>asset_path</code> helper in CoffeeScript files with <code>erb</code>
extension (e.g., <code>application.coffee.erb</code>):</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$('#logo').attr src: "<%= asset_path('logo.png') %>"
</pre>
</div>
<h4 id="manifest-files-and-directives"><a class="anchorlink" href="#manifest-files-and-directives">2.4 Manifest Files and Directives</a></h4><p>Sprockets uses manifest files to determine which assets to include and serve.
These manifest files contain <em>directives</em> - instructions that tell Sprockets
which files to require in order to build a single CSS or JavaScript file. With
these directives, Sprockets loads the files specified, processes them if
necessary, concatenates them into one single file, and then compresses them
(based on value of <code>Rails.application.config.assets.js_compressor</code>). By serving
one file rather than many, the load time of pages can be greatly reduced because
the browser makes fewer requests. Compression also reduces file size, enabling
the browser to download them faster.</p><p>For example, with a <code>app/assets/javascripts/application.js</code> file containing the
following lines:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
// ...
//= require rails-ujs
//= require turbolinks
//= require_tree .
</pre>
</div>
<p>In JavaScript files, Sprockets directives begin with <code>//=</code>. In the above case,
the file is using the <code>require</code> and the <code>require_tree</code> directives. The <code>require</code>
directive is used to tell Sprockets the files you wish to require. Here, you are
requiring the files <code>rails-ujs.js</code> and <code>turbolinks.js</code> that are available somewhere
in the search path for Sprockets. You need not supply the extensions explicitly.
Sprockets assumes you are requiring a <code>.js</code> file when done from within a <code>.js</code>
file.</p><p>The <code>require_tree</code> directive tells Sprockets to recursively include <em>all</em>
JavaScript files in the specified directory into the output. These paths must be
specified relative to the manifest file. You can also use the
<code>require_directory</code> directive which includes all JavaScript files only in the
directory specified, without recursion.</p><p>Directives are processed top to bottom, but the order in which files are
included by <code>require_tree</code> is unspecified. You should not rely on any particular
order among those. If you need to ensure some particular JavaScript ends up
above some other in the concatenated file, require the prerequisite file first
in the manifest. Note that the family of <code>require</code> directives prevents files
from being included twice in the output.</p><p>Rails also creates a default <code>app/assets/stylesheets/application.css</code> file
which contains these lines:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
/* ...
*= require_self
*= require_tree .
*/
</pre>
</div>
<p>Rails create <code>app/assets/stylesheets/application.css</code> regardless of whether the
--skip-sprockets option is used when creating a new Rails application. This is
so you can easily add asset pipelining later if you like.</p><p>The directives that work in JavaScript files also work in stylesheets
(though obviously including stylesheets rather than JavaScript files). The
<code>require_tree</code> directive in a CSS manifest works the same way as the JavaScript
one, requiring all stylesheets from the current directory.</p><p>In this example, <code>require_self</code> is used. This puts the CSS contained within the
file (if any) at the precise location of the <code>require_self</code> call.</p><div class="note"><p>If you want to use multiple Sass files, you should generally use the <a href="https://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#import">Sass <code>@import</code> rule</a>
instead of these Sprockets directives. When using Sprockets directives, Sass files exist within
their own scope, making variables or mixins only available within the document they were defined in.</p></div><p>You can do file globbing as well using <code>@import "*"</code>, and <code>@import "**/*"</code> to add the whole tree which is equivalent to how <code>require_tree</code> works. Check the <a href="https://github.com/rails/sass-rails#features">sass-rails documentation</a> for more info and important caveats.</p><p>You can have as many manifest files as you need. For example, the <code>admin.css</code>
and <code>admin.js</code> manifest could contain the JS and CSS files that are used for the
admin section of an application.</p><p>The same remarks about ordering made above apply. In particular, you can specify
individual files and they are compiled in the order specified. For example, you
might concatenate three CSS files together this way:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
/* ...
*= require reset
*= require layout
*= require chrome
*/
</pre>
</div>
<h4 id="preprocessing"><a class="anchorlink" href="#preprocessing">2.5 Preprocessing</a></h4><p>The file extensions used on an asset determine what preprocessing is applied.
When a controller or a scaffold is generated with the default Rails gemset, a
CoffeeScript file and a SCSS file are generated in place of a regular JavaScript
and CSS file. The example used before was a controller called "projects", which
generated an <code>app/assets/stylesheets/projects.scss</code> file.</p><p>In development mode, or if the asset pipeline is disabled, when these files are
requested they are processed by the processors provided by the <code>coffee-script</code>
and <code>sass</code> gems and then sent back to the browser as JavaScript and CSS
respectively. When asset pipelining is enabled, these files are preprocessed and
placed in the <code>public/assets</code> directory for serving by either the Rails app or
web server.</p><p>Additional layers of preprocessing can be requested by adding other extensions,
where each extension is processed in a right-to-left manner. These should be
used in the order the processing should be applied. For example, a stylesheet
called <code>app/assets/stylesheets/projects.scss.erb</code> is first processed as ERB,
then SCSS, and finally served as CSS. The same applies to a JavaScript file -
<code>app/assets/javascripts/projects.coffee.erb</code> is processed as ERB, then
CoffeeScript, and served as JavaScript.</p><p>Keep in mind the order of these preprocessors is important. For example, if
you called your JavaScript file <code>app/assets/javascripts/projects.erb.coffee</code>
then it would be processed with the CoffeeScript interpreter first, which
wouldn't understand ERB and therefore you would run into problems.</p><h3 id="in-development"><a class="anchorlink" href="#in-development">3 In Development</a></h3><p>In development mode, assets are served as separate files in the order they are
specified in the manifest file.</p><p>This manifest <code>app/assets/javascripts/application.js</code>:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
//= require core
//= require projects
//= require tickets
</pre>
</div>
<p>would generate this HTML:</p><div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<script src="/assets/core.js?body=1"></script>
<script src="/assets/projects.js?body=1"></script>
<script src="/assets/tickets.js?body=1"></script>
</pre>
</div>
<p>The <code>body</code> param is required by Sprockets.</p><h4 id="raise-an-error-when-an-asset-is-not-found"><a class="anchorlink" href="#raise-an-error-when-an-asset-is-not-found">3.1 Raise an Error When an Asset is Not Found</a></h4><p>If you are using sprockets-rails >= 3.2.0 you can configure what happens
when an asset lookup is performed and nothing is found. If you turn off "asset fallback"
then an error will be raised when an asset cannot be found.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.assets.unknown_asset_fallback = false
</pre>
</div>
<p>If "asset fallback" is enabled then when an asset cannot be found the path will be
output instead and no error raised. The asset fallback behavior is enabled by default.</p><h4 id="turning-digests-off"><a class="anchorlink" href="#turning-digests-off">3.2 Turning Digests Off</a></h4><p>You can turn off digests by updating <code>config/environments/development.rb</code> to
include:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.assets.digest = false
</pre>
</div>
<p>When this option is true, digests will be generated for asset URLs.</p><h4 id="turning-debugging-off"><a class="anchorlink" href="#turning-debugging-off">3.3 Turning Debugging Off</a></h4><p>You can turn off debug mode by updating <code>config/environments/development.rb</code> to
include:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.assets.debug = false
</pre>
</div>
<p>When debug mode is off, Sprockets concatenates and runs the necessary
preprocessors on all files. With debug mode turned off the manifest above would
generate instead:</p><div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<script src="/assets/application.js"></script>
</pre>
</div>
<p>Assets are compiled and cached on the first request after the server is started.
Sprockets sets a <code>must-revalidate</code> Cache-Control HTTP header to reduce request
overhead on subsequent requests - on these the browser gets a 304 (Not Modified)
response.</p><p>If any of the files in the manifest have changed between requests, the server
responds with a new compiled file.</p><p>Debug mode can also be enabled in Rails helper methods:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= stylesheet_link_tag "application", debug: true %>
<%= javascript_include_tag "application", debug: true %>
</pre>
</div>
<p>The <code>:debug</code> option is redundant if debug mode is already on.</p><p>You can also enable compression in development mode as a sanity check, and
disable it on-demand as required for debugging.</p><h3 id="in-production"><a class="anchorlink" href="#in-production">4 In Production</a></h3><p>In the production environment Sprockets uses the fingerprinting scheme outlined
above. By default Rails assumes assets have been precompiled and will be
served as static assets by your web server.</p><p>During the precompilation phase an SHA256 is generated from the contents of the
compiled files, and inserted into the filenames as they are written to disk.
These fingerprinted names are used by the Rails helpers in place of the manifest
name.</p><p>For example this:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= javascript_include_tag "application" %>
<%= stylesheet_link_tag "application" %>
</pre>
</div>
<p>generates something like this:</p><div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<script src="/assets/application-908e25f4bf641868d8683022a5b62f54.js"></script>
<link href="/assets/application-4dd5b109ee3439da54f5bdfd78a80473.css" media="screen"
rel="stylesheet" />
</pre>
</div>
<div class="note"><p>with the Asset Pipeline the <code>:cache</code> and <code>:concat</code> options aren't used
anymore, delete these options from the <code>javascript_include_tag</code> and
<code>stylesheet_link_tag</code>.</p></div><p>The fingerprinting behavior is controlled by the <code>config.assets.digest</code>
initialization option (which defaults to <code>true</code>).</p><div class="note"><p>Under normal circumstances the default <code>config.assets.digest</code> option
should not be changed. If there are no digests in the filenames, and far-future
headers are set, remote clients will never know to refetch the files when their
content changes.</p></div><h4 id="precompiling-assets"><a class="anchorlink" href="#precompiling-assets">4.1 Precompiling Assets</a></h4><p>Rails comes bundled with a command to compile the asset manifests and other
files in the pipeline.</p><p>Compiled assets are written to the location specified in <code>config.assets.prefix</code>.
By default, this is the <code>/assets</code> directory.</p><p>You can call this command on the server during deployment to create compiled
versions of your assets directly on the server. See the next section for
information on compiling locally.</p><p>The command is:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ RAILS_ENV=production rails assets:precompile
</pre>
</div>
<p>Capistrano (v2.15.1 and above) includes a recipe to handle this in deployment.
Add the following line to <code>Capfile</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
load 'deploy/assets'
</pre>
</div>
<p>This links the folder specified in <code>config.assets.prefix</code> to <code>shared/assets</code>.
If you already use this shared folder you'll need to write your own deployment
command.</p><p>It is important that this folder is shared between deployments so that remotely
cached pages referencing the old compiled assets still work for the life of
the cached page.</p><p>The default matcher for compiling files includes <code>application.js</code>,
<code>application.css</code> and all non-JS/CSS files (this will include all image assets
automatically) from <code>app/assets</code> folders including your gems:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
[ Proc.new { |filename, path| path =~ /app\/assets/ && !%w(.js .css).include?(File.extname(filename)) },
/application.(css|js)$/ ]
</pre>
</div>
<div class="note"><p>The matcher (and other members of the precompile array; see below) is
applied to final compiled file names. This means anything that compiles to
JS/CSS is excluded, as well as raw JS/CSS files; for example, <code>.coffee</code> and
<code>.scss</code> files are <strong>not</strong> automatically included as they compile to JS/CSS.</p></div><p>If you have other manifests or individual stylesheets and JavaScript files to
include, you can add them to the <code>precompile</code> array in <code>config/initializers/assets.rb</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Rails.application.config.assets.precompile += %w( admin.js admin.css )
</pre>
</div>
<div class="note"><p>Always specify an expected compiled filename that ends with <code>.js</code> or <code>.css</code>,
even if you want to add Sass or CoffeeScript files to the precompile array.</p></div><p>The command also generates a <code>.sprockets-manifest-randomhex.json</code> (where <code>randomhex</code> is
a 16-byte random hex string) that contains a list with all your assets and their respective
fingerprints. This is used by the Rails helper methods to avoid handing the
mapping requests back to Sprockets. A typical manifest file looks like:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
{"files":{"application-aee4be71f1288037ae78b997df388332edfd246471b533dcedaa8f9fe156442b.js":{"logical_path":"application.js","mtime":"2016-12-23T20:12:03-05:00","size":412383,
"digest":"aee4be71f1288037ae78b997df388332edfd246471b533dcedaa8f9fe156442b","integrity":"sha256-ruS+cfEogDeueLmX3ziDMu39JGRxtTPc7aqPn+FWRCs="},
"application-86a292b5070793c37e2c0e5f39f73bb387644eaeada7f96e6fc040a028b16c18.css":{"logical_path":"application.css","mtime":"2016-12-23T19:12:20-05:00","size":2994,
"digest":"86a292b5070793c37e2c0e5f39f73bb387644eaeada7f96e6fc040a028b16c18","integrity":"sha256-hqKStQcHk8N+LA5fOfc7s4dkTq6tp/lub8BAoCixbBg="},
"favicon-8d2387b8d4d32cecd93fa3900df0e9ff89d01aacd84f50e780c17c9f6b3d0eda.ico":{"logical_path":"favicon.ico","mtime":"2016-12-23T20:11:00-05:00","size":8629,
"digest":"8d2387b8d4d32cecd93fa3900df0e9ff89d01aacd84f50e780c17c9f6b3d0eda","integrity":"sha256-jSOHuNTTLOzZP6OQDfDp/4nQGqzYT1DngMF8n2s9Dto="},
"my_image-f4028156fd7eca03584d5f2fc0470df1e0dbc7369eaae638b2ff033f988ec493.png":{"logical_path":"my_image.png","mtime":"2016-12-23T20:10:54-05:00","size":23414,
"digest":"f4028156fd7eca03584d5f2fc0470df1e0dbc7369eaae638b2ff033f988ec493","integrity":"sha256-9AKBVv1+ygNYTV8vwEcN8eDbxzaequY4sv8DP5iOxJM="}},
"assets":{"application.js":"application-aee4be71f1288037ae78b997df388332edfd246471b533dcedaa8f9fe156442b.js",
"application.css":"application-86a292b5070793c37e2c0e5f39f73bb387644eaeada7f96e6fc040a028b16c18.css",
"favicon.ico":"favicon-8d2387b8d4d32cecd93fa3900df0e9ff89d01aacd84f50e780c17c9f6b3d0eda.ico",
"my_image.png":"my_image-f4028156fd7eca03584d5f2fc0470df1e0dbc7369eaae638b2ff033f988ec493.png"}}
</pre>
</div>
<p>The default location for the manifest is the root of the location specified in
<code>config.assets.prefix</code> ('/assets' by default).</p><div class="note"><p>If there are missing precompiled files in production you will get a
<code>Sprockets::Helpers::RailsHelper::AssetPaths::AssetNotPrecompiledError</code>
exception indicating the name of the missing file(s).</p></div><h5 id="far-future-expires-header"><a class="anchorlink" href="#far-future-expires-header">4.1.1 Far-future Expires Header</a></h5><p>Precompiled assets exist on the file system and are served directly by your web
server. They do not have far-future headers by default, so to get the benefit of
fingerprinting you'll have to update your server configuration to add those
headers.</p><p>For Apache:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
# The Expires* directives requires the Apache module
# `mod_expires` to be enabled.
<Location /assets/>
# Use of ETag is discouraged when Last-Modified is present
Header unset ETag
FileETag None
# RFC says only cache for 1 year
ExpiresActive On
ExpiresDefault "access plus 1 year"
</Location>
</pre>
</div>
<p>For NGINX:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
location ~ ^/assets/ {
expires 1y;
add_header Cache-Control public;
add_header ETag "";
}
</pre>
</div>
<h4 id="local-precompilation"><a class="anchorlink" href="#local-precompilation">4.2 Local Precompilation</a></h4><p>There are several reasons why you might want to precompile your assets locally.
Among them are:</p>
<ul>
<li>You may not have write access to your production file system.</li>
<li>You may be deploying to more than one server, and want to avoid
duplication of work.</li>
<li>You may be doing frequent deploys that do not include asset changes.</li>
</ul>
<p>Local compilation allows you to commit the compiled files into source control,
and deploy as normal.</p><p>There are three caveats:</p>
<ul>
<li>You must not run the Capistrano deployment task that precompiles assets.</li>
<li>You must ensure any necessary compressors or minifiers are
available on your development system.</li>
<li>You must change the following application configuration setting:</li>
</ul>
<p>In <code>config/environments/development.rb</code>, place the following line:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.assets.prefix = "/dev-assets"
</pre>
</div>
<p>The <code>prefix</code> change makes Sprockets use a different URL for serving assets in
development mode, and pass all requests to Sprockets. The prefix is still set to
<code>/assets</code> in the production environment. Without this change, the application
would serve the precompiled assets from <code>/assets</code> in development, and you would
not see any local changes until you compile assets again.</p><p>In practice, this will allow you to precompile locally, have those files in your
working tree, and commit those files to source control when needed. Development
mode will work as expected.</p><h4 id="live-compilation"><a class="anchorlink" href="#live-compilation">4.3 Live Compilation</a></h4><p>In some circumstances you may wish to use live compilation. In this mode all
requests for assets in the pipeline are handled by Sprockets directly.</p><p>To enable this option set:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.assets.compile = true
</pre>
</div>
<p>On the first request the assets are compiled and cached as outlined in
development above, and the manifest names used in the helpers are altered to
include the SHA256 hash.</p><p>Sprockets also sets the <code>Cache-Control</code> HTTP header to <code>max-age=31536000</code>. This
signals all caches between your server and the client browser that this content
(the file served) can be cached for 1 year. The effect of this is to reduce the
number of requests for this asset from your server; the asset has a good chance
of being in the local browser cache or some intermediate cache.</p><p>This mode uses more memory, performs more poorly than the default, and is not
recommended.</p><p>If you are deploying a production application to a system without any
pre-existing JavaScript runtimes, you may want to add one to your <code>Gemfile</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
group :production do
gem 'mini_racer'
end
</pre>
</div>
<h4 id="cdns"><a class="anchorlink" href="#cdns">4.4 CDNs</a></h4><p>CDN stands for <a href="https://en.wikipedia.org/wiki/Content_delivery_network">Content Delivery
Network</a>, they are
primarily designed to cache assets all over the world so that when a browser
requests the asset, a cached copy will be geographically close to that browser.
If you are serving assets directly from your Rails server in production, the
best practice is to use a CDN in front of your application.</p><p>A common pattern for using a CDN is to set your production application as the
"origin" server. This means when a browser requests an asset from the CDN and
there is a cache miss, it will grab the file from your server on the fly and
then cache it. For example if you are running a Rails application on
<code>example.com</code> and have a CDN configured at <code>mycdnsubdomain.fictional-cdn.com</code>,
then when a request is made to <code>mycdnsubdomain.fictional-
cdn.com/assets/smile.png</code>, the CDN will query your server once at
<code>example.com/assets/smile.png</code> and cache the request. The next request to the
CDN that comes in to the same URL will hit the cached copy. When the CDN can
serve an asset directly the request never touches your Rails server. Since the
assets from a CDN are geographically closer to the browser, the request is
faster, and since your server doesn't need to spend time serving assets, it can
focus on serving application code as fast as possible.</p><h5 id="set-up-a-cdn-to-serve-static-assets"><a class="anchorlink" href="#set-up-a-cdn-to-serve-static-assets">4.4.1 Set up a CDN to Serve Static Assets</a></h5><p>To set up your CDN you have to have your application running in production on
the internet at a publicly available URL, for example <code>example.com</code>. Next
you'll need to sign up for a CDN service from a cloud hosting provider. When you
do this you need to configure the "origin" of the CDN to point back at your
website <code>example.com</code>, check your provider for documentation on configuring the
origin server.</p><p>The CDN you provisioned should give you a custom subdomain for your application
such as <code>mycdnsubdomain.fictional-cdn.com</code> (note fictional-cdn.com is not a
valid CDN provider at the time of this writing). Now that you have configured
your CDN server, you need to tell browsers to use your CDN to grab assets
instead of your Rails server directly. You can do this by configuring Rails to
set your CDN as the asset host instead of using a relative path. To set your
asset host in Rails, you need to set <code>config.action_controller.asset_host</code> in
<code>config/environments/production.rb</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.action_controller.asset_host = 'mycdnsubdomain.fictional-cdn.com'
</pre>
</div>
<div class="note"><p>You only need to provide the "host", this is the subdomain and root
domain, you do not need to specify a protocol or "scheme" such as <code>http://</code> or
<code>https://</code>. When a web page is requested, the protocol in the link to your asset
that is generated will match how the webpage is accessed by default.</p></div><p>You can also set this value through an <a href="https://en.wikipedia.org/wiki/Environment_variable">environment
variable</a> to make running a
staging copy of your site easier:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
config.action_controller.asset_host = ENV['CDN_HOST']
</pre>
</div>
<div class="note"><p>You would need to set <code>CDN_HOST</code> on your server to <code>mycdnsubdomain
.fictional-cdn.com</code> for this to work.</p></div><p>Once you have configured your server and your CDN when you serve a webpage that
has an asset:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= asset_path('smile.png') %>
</pre>
</div>
<p>Instead of returning a path such as <code>/assets/smile.png</code> (digests are left out
for readability). The URL generated will have the full path to your CDN.</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
http://mycdnsubdomain.fictional-cdn.com/assets/smile.png
</pre>
</div>
<p>If the CDN has a copy of <code>smile.png</code> it will serve it to the browser and your
server doesn't even know it was requested. If the CDN does not have a copy it
will try to find it at the "origin" <code>example.com/assets/smile.png</code> and then store
it for future use.</p><p>If you want to serve only some assets from your CDN, you can use custom <code>:host</code>
option your asset helper, which overwrites value set in
<code>config.action_controller.asset_host</code>.</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= asset_path 'image.png', host: 'mycdnsubdomain.fictional-cdn.com' %>
</pre>
</div>
<h5 id="customize-cdn-caching-behavior"><a class="anchorlink" href="#customize-cdn-caching-behavior">4.4.2 Customize CDN Caching Behavior</a></h5><p>A CDN works by caching content. If the CDN has stale or bad content, then it is
hurting rather than helping your application. The purpose of this section is to
describe general caching behavior of most CDNs, your specific provider may
behave slightly differently.</p><h6 id="cdn-request-caching"><a class="anchorlink" href="#cdn-request-caching">4.4.2.1 CDN Request Caching</a></h6><p>While a CDN is described as being good for caching assets, in reality caches the
entire request. This includes the body of the asset as well as any headers. The
most important one being <code>Cache-Control</code> which tells the CDN (and web browsers)
how to cache contents. This means that if someone requests an asset that does
not exist <code>/assets/i-dont-exist.png</code> and your Rails application returns a 404,
then your CDN will likely cache the 404 page if a valid <code>Cache-Control</code> header
is present.</p><h6 id="cdn-header-debugging"><a class="anchorlink" href="#cdn-header-debugging">4.4.2.2 CDN Header Debugging</a></h6><p>One way to check the headers are cached properly in your CDN is by using <a href="https://explainshell.com/explain?cmd=curl+-I+http%3A%2F%2Fwww.example.com">curl</a>. You
can request the headers from both your server and your CDN to verify they are
the same:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ curl -I http://www.example/assets/application-
d0e099e021c95eb0de3615fd1d8c4d83.css
HTTP/1.1 200 OK
Server: Cowboy
Date: Sun, 24 Aug 2014 20:27:50 GMT
Connection: keep-alive
Last-Modified: Thu, 08 May 2014 01:24:14 GMT