-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasset_pipeline.html
1195 lines (1102 loc) · 70.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="zh-TW">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>The Asset Pipeline — Ruby on Rails 指南</title>
<meta name="description" content="Ruby on Rails 指南:系統學習 Rails(Rails 4.2 版本)" >
<meta name="keywords" content="Ruby on Rails Guides 指南 中文 學習 免費 網路 Web 開發" >
<meta name="author" content="http://git.io/G_R1sA">
<meta property="fb:admins" content="1340181291">
<meta property="og:title" content="The Asset Pipeline — Ruby on Rails 指南" >
<meta property="og:site_name" content="Ruby on Rails 指南">
<meta property="og:image" content="http://rails.ruby.tw/images/rails_guides_cover.jpg">
<meta property="og:url" content="http://rails.ruby.tw/">
<meta property="og:type" content="article">
<meta property="og:description" content="Ruby on Rails 指南:系統學習 Rails(Rails 4.2 版本)">
<link rel="stylesheet" href="stylesheets/application.css">
<link href="http://fonts.googleapis.com/css?family=Noto+Sans:400,700|Noto+Serif:700|Source+Code+Pro" rel="stylesheet">
<link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon">
</head>
<body class="guide">
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/zh-TW/sdk.js#xfbml=1&appId=837401439623727&version=v2.0";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<script type="text/javascript">
window.twttr=(function(d,s,id){var t,js,fjs=d.getElementsByTagName(s)[0];if(d.getElementById(id)){return}js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);return window.twttr||(t={_e:[],ready:function(f){t._e.push(f)}})}(document,"script","twitter-wjs"));
</script>
<div id="topNav">
<div class="wrapper">
<strong class="more-info-label">更多內容 <a href="http://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="http://rubyonrails.org/">綜覽</a></li>
<li class="more-info"><a href="http://rubyonrails.org/download">下載</a></li>
<li class="more-info"><a href="http://rubyonrails.org/deploy">部署</a></li>
<li class="more-info"><a href="https://github.com/rails/rails">原始碼</a></li>
<li class="more-info"><a href="http://rubyonrails.org/screencasts">影片</a></li>
<li class="more-info"><a href="http://rubyonrails.org/documentation">文件</a></li>
<li class="more-info"><a href="http://rubyonrails.org/community">社群</a></li>
<li class="more-info"><a href="http://weblog.rubyonrails.org/">Blog</a></li>
</ul>
</div>
</div>
<div id="header">
<div class="wrapper clearfix">
<h1><a href="index.html" title="回首頁">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>
<dl class="L">
<dt>起步走</dt>
<dd><a href="getting_started.html">Rails 起步走</a></dd>
<dt>Models</dt>
<dd><a href="active_record_basics.html">Active Record 基礎</a></dd>
<dd><a href="active_record_migrations.html">Active Record 遷移</a></dd>
<dd><a href="active_record_validations.html">Active Record 驗證</a></dd>
<dd><a href="active_record_callbacks.html">Active Record 回呼</a></dd>
<dd><a href="association_basics.html">Active Record 關聯</a></dd>
<dd><a href="active_record_querying.html">Active Record 查詢</a></dd>
<dt>Views</dt>
<dd><a href="layouts_and_rendering.html">Rails 算繪與版型</a></dd>
<dd><a href="form_helpers.html">Action View 表單輔助方法</a></dd>
<dt>Controllers</dt>
<dd><a href="action_controller_overview.html">Action Controller 綜覽</a></dd>
<dd><a href="routing.html">Rails 路由:深入淺出</a></dd>
</dl>
<dl class="R">
<dt>深入了解</dt>
<dd><a href="active_support_core_extensions.html">Active Support 核心擴展</a></dd>
<dd><a href="i18n.html">Rails 國際化 API</a></dd>
<dd><a href="action_mailer_basics.html">Action Mailer 基礎</a></dd>
<dd><a href="active_job_basics.html">Active Job 基礎</a></dd>
<dd><a href="security.html">Rails 安全指南</a></dd>
<dd><a href="debugging_rails_applications.html">除錯 Rails 應用程式</a></dd>
<dd><a href="configuring.html">Rails 應用程式設定</a></dd>
<dd><a href="command_line.html">Rake 任務與 Rails 命令列工具</a></dd>
<dd><a href="asset_pipeline.html">Asset Pipeline</a></dd>
<dd><a href="working_with_javascript_in_rails.html">在 Rails 使用 JavaScript</a></dd>
<dd><a href="constant_autoloading_and_reloading.html">Constant Autoloading and Reloading</a></dd>
<dt>擴充 Rails</dt>
<dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
<dd><a href="generators.html">客製與新建 Rails 產生器</a></dd>
<dd><a href="rails_application_templates.html">Rails 應用程式模版</a></dd>
<dt>貢獻 Ruby on Rails</dt>
<dd><a href="contributing_to_ruby_on_rails.html">貢獻 Ruby on Rails</a></dd>
<dd><a href="api_documentation_guidelines.html">API 文件準則</a></dd>
<dd><a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails 指南準則</a></dd>
<dt>維護方針</dt>
<dd><a href="maintenance_policy.html">維護方針</a></dd>
<dt>發佈記</dt>
<dd><a href="upgrading_ruby_on_rails.html">升級 Ruby on Rails</a></dd>
<dd><a href="4_2_release_notes.html">Ruby on Rails 4.2 發佈記</a></dd>
<dd><a href="4_1_release_notes.html">Ruby on Rails 4.1 發佈記</a></dd>
<dd><a href="4_0_release_notes.html">Ruby on Rails 4.0 發佈記</a></dd>
<dd><a href="3_2_release_notes.html">Ruby on Rails 3.2 發佈記</a></dd>
<dd><a href="3_1_release_notes.html">Ruby on Rails 3.1 發佈記</a></dd>
<dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 發佈記</a></dd>
<dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 發佈記</a></dd>
<dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 發佈記</a></dd>
<dt>Rails 指南翻譯術語</dt>
<dd><a href="translation_terms.html">翻譯術語</a></dd>
</dl>
</div>
</li>
<li><a class="nav-item" href="//github.com/docrails-tw/guides">貢獻翻譯</a></li>
<li><a class="nav-item" href="contributing_to_ruby_on_rails.html">貢獻</a></li>
<li><a class="nav-item" href="credits.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">Rails 起步走</option>
</optgroup>
<optgroup label="Models">
<option value="active_record_basics.html">Active Record 基礎</option>
<option value="active_record_migrations.html">Active Record 遷移</option>
<option value="active_record_validations.html">Active Record 驗證</option>
<option value="active_record_callbacks.html">Active Record 回呼</option>
<option value="association_basics.html">Active Record 關聯</option>
<option value="active_record_querying.html">Active Record 查詢</option>
</optgroup>
<optgroup label="Views">
<option value="layouts_and_rendering.html">Rails 算繪與版型</option>
<option value="form_helpers.html">Action View 表單輔助方法</option>
</optgroup>
<optgroup label="Controllers">
<option value="action_controller_overview.html">Action Controller 綜覽</option>
<option value="routing.html">Rails 路由:深入淺出</option>
</optgroup>
<optgroup label="深入了解">
<option value="active_support_core_extensions.html">Active Support 核心擴展</option>
<option value="i18n.html">Rails 國際化 API</option>
<option value="action_mailer_basics.html">Action Mailer 基礎</option>
<option value="active_job_basics.html">Active Job 基礎</option>
<option value="security.html">Rails 安全指南</option>
<option value="debugging_rails_applications.html">除錯 Rails 應用程式</option>
<option value="configuring.html">Rails 應用程式設定</option>
<option value="command_line.html">Rake 任務與 Rails 命令列工具</option>
<option value="asset_pipeline.html">Asset Pipeline</option>
<option value="working_with_javascript_in_rails.html">在 Rails 使用 JavaScript</option>
<option value="constant_autoloading_and_reloading.html">Constant Autoloading and Reloading</option>
</optgroup>
<optgroup label="擴充 Rails">
<option value="rails_on_rack.html">Rails on Rack</option>
<option value="generators.html">客製與新建 Rails 產生器</option>
<option value="rails_application_templates.html">Rails 應用程式模版</option>
</optgroup>
<optgroup label="貢獻 Ruby on Rails">
<option value="contributing_to_ruby_on_rails.html">貢獻 Ruby on Rails</option>
<option value="api_documentation_guidelines.html">API 文件準則</option>
<option value="ruby_on_rails_guides_guidelines.html">Ruby on Rails 指南準則</option>
</optgroup>
<optgroup label="維護方針">
<option value="maintenance_policy.html">維護方針</option>
</optgroup>
<optgroup label="發佈記">
<option value="upgrading_ruby_on_rails.html">升級 Ruby on Rails</option>
<option value="4_2_release_notes.html">Ruby on Rails 4.2 發佈記</option>
<option value="4_1_release_notes.html">Ruby on Rails 4.1 發佈記</option>
<option value="4_0_release_notes.html">Ruby on Rails 4.0 發佈記</option>
<option value="3_2_release_notes.html">Ruby on Rails 3.2 發佈記</option>
<option value="3_1_release_notes.html">Ruby on Rails 3.1 發佈記</option>
<option value="3_0_release_notes.html">Ruby on Rails 3.0 發佈記</option>
<option value="2_3_release_notes.html">Ruby on Rails 2.3 發佈記</option>
<option value="2_2_release_notes.html">Ruby on Rails 2.2 發佈記</option>
</optgroup>
<optgroup label="Rails 指南翻譯術語">
<option value="translation_terms.html">翻譯術語</option>
</optgroup>
</select>
</li>
</ul>
</div>
</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="#runtime-error-checking">Runtime Error Checking</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="#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>
<li><a href="#upgrading-from-old-versions-of-rails">Upgrading from Old Versions of Rails</a></li>
</ol>
</div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<h3 id="what-is-the-asset-pipeline-questionmark">1 What is the Asset Pipeline?</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.</p><p>The asset pipeline is technically no longer a core feature of Rails 4, it has
been extracted out of the framework into the
<a href="https://github.com/rails/sprockets-rails">sprockets-rails</a> gem.</p><p>The asset pipeline is enabled by default.</p><p>You can disable the asset pipeline 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 4 automatically adds the <code>sass-rails</code>, <code>coffee-rails</code> and <code>uglifier</code>
gems to your Gemfile, which are used by Sprockets for asset compression:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
gem 'sass-rails'
gem 'uglifier'
gem 'coffee-rails'
</pre>
</div>
<p>Using the <code>--skip-sprockets</code> option will prevent Rails 4 from adding
<code>sass-rails</code> and <code>uglifier</code> to Gemfile, so if you later want to enable
the asset pipeline you will have to add those gems to your Gemfile. 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 Gemfile and no <code>config.assets.css_compressor</code> option is set.</p></div><h4 id="main-features">1.1 Main Features</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 MD5 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">1.2 What is Fingerprinting and Why Should I Care?</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><br>
<a href="http://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><br>
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><br>
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 production and disabled for all other
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="http://code.google.com/speed/page-speed/docs/caching.html">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">2 How to Use the Asset Pipeline</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. 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">2.1 Controller Specific Assets</h4><p>When you generate a scaffold or a controller, Rails also generates a JavaScript
file (or CoffeeScript file if the <code>coffee-rails</code> gem is in the <code>Gemfile</code>) and 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 scaffolds.css (or scaffolds.css.scss 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/javascripts/projects.js.coffee</code> and another at
<code>app/assets/stylesheets/projects.css.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 .coffee and .scss 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 Mac OS X or Windows, you have a JavaScript runtime installed in
your operating system. Check
<a href="https://github.com/sstephenson/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">2.2 Asset Organization</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.</p></li>
</ul>
<div class="warning"><p>If you are upgrading from Rails 3, please take into account that assets
under <code>lib/assets</code> or <code>vendor/assets</code> are available for inclusion via the
application manifests but no longer part of the precompile array. See
<a href="#precompiling-assets">Precompiling Assets</a> for guidance.</p></div><h5 id="search-paths">2.2.1 Search Paths</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/application.rb</code>. For example:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
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">2.2.2 Using Index Files</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">2.3 Coding Links to Assets</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 4, 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" => true %>
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
</pre>
</div>
<p>In regular views you can access images in the <code>public/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 MD5 hash such as
<code>public/assets/rails-af27b6a414e6da00003503148be9b409.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">2.3.1 CSS and ERB</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="http://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">2.3.2 CSS and Sass</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> becomes <code>url(/assets/rails.png)</code>
</li>
<li>
<code>image-path("rails.png")</code> becomes <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> becomes <code>url(/assets/rails.png)</code>
</li>
<li>
<code>asset-path("rails.png")</code> becomes <code>"/assets/rails.png"</code>
</li>
</ul>
<h5 id="javascript-coffeescript-and-erb">2.3.3 JavaScript/CoffeeScript and ERB</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.js.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">2.4 Manifest Files and Directives</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 (if
<code>Rails.application.config.assets.compress</code> is true). 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, a new Rails 4 application includes a default
<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 jquery
//= require jquery_ujs
//= 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>jquery.js</code> and <code>jquery_ujs.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 4 creates both <code>app/assets/javascripts/application.js</code> and
<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. If
<code>require_self</code> is called more than once, only the last call is respected.</p><div class="note"><p>If you want to use multiple Sass files, you should generally use the <a href="http://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">2.5 Preprocessing</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/javascripts/projects.js.coffee</code> and an
<code>app/assets/stylesheets/projects.css.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.css.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.js.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.js.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">3 In Development</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="runtime-error-checking">3.1 Runtime Error Checking</h4><p>By default the asset pipeline will check for potential errors in development mode during
runtime. To disable this behavior you can set:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.assets.raise_runtime_errors = false
</pre>
</div>
<p>When this option is true, the asset pipeline will check if all the assets loaded
in your application are included in the <code>config.assets.precompile</code> list.
If <code>config.assets.digest</code> is also true, the asset pipeline will require that
all requests for assets include digests.</p><h4 id="turning-digests-off">3.2 Turning Digests Off</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">3.3 Turning Debugging Off</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">4 In Production</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 MD5 is generated from the contents of the
compiled files, and inserted into the filenames as they are written to disc.
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>
<p>Note: with the Asset Pipeline the :cache and :concat options aren't used
anymore, delete these options from the <code>javascript_include_tag</code> and
<code>stylesheet_link_tag</code>.</p><p>The fingerprinting behavior is controlled by the <code>config.assets.digest</code>
initialization option (which defaults to <code>true</code> for production and <code>false</code> for
everything else).</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">4.1 Precompiling Assets</h4><p>Rails comes bundled with a rake task 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 task 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 rake task is:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ RAILS_ENV=production bin/rake 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
task.</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 += ['admin.js', 'admin.css', 'swfObject.js']
</pre>
</div>
<p>Or, you can opt to precompile all assets with something like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# config/initializers/assets.rb
Rails.application.config.assets.precompile << Proc.new do |path|
if path =~ /\.(css|js)\z/
full_path = Rails.application.assets.resolve(path).to_path
app_assets_path = Rails.root.join('app', 'assets').to_path
if full_path.starts_with? app_assets_path
puts "including asset: " + full_path
true
else
puts "excluding asset: " + full_path
false
end
else
false
end
end
</pre>
</div>
<div class="note"><p>Always specify an expected compiled filename that ends with .js or .css,
even if you want to add Sass or CoffeeScript files to the precompile array.</p></div><p>The rake task also generates a <code>manifest-md5hash.json</code> 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-723d1be6cc741a3aabb1cec24276d681.js":{"logical_path":"application.js","mtime":"2013-07-26T22:55:03-07:00","size":302506,
"digest":"723d1be6cc741a3aabb1cec24276d681"},"application-12b3c7dd74d2e9df37e7cbb1efa76a6d.css":{"logical_path":"application.css","mtime":"2013-07-26T22:54:54-07:00","size":1560,
"digest":"12b3c7dd74d2e9df37e7cbb1efa76a6d"},"application-1c5752789588ac18d7e1a50b1f0fd4c2.css":{"logical_path":"application.css","mtime":"2013-07-26T22:56:17-07:00","size":1591,
"digest":"1c5752789588ac18d7e1a50b1f0fd4c2"},"favicon-a9c641bf2b81f0476e876f7c5e375969.ico":{"logical_path":"favicon.ico","mtime":"2013-07-26T23:00:10-07:00","size":1406,
"digest":"a9c641bf2b81f0476e876f7c5e375969"},"my_image-231a680f23887d9dd70710ea5efd3c62.png":{"logical_path":"my_image.png","mtime":"2013-07-26T23:00:27-07:00","size":6646,
"digest":"231a680f23887d9dd70710ea5efd3c62"}},"assets":{"application.js":
"application-723d1be6cc741a3aabb1cec24276d681.js","application.css":
"application-1c5752789588ac18d7e1a50b1f0fd4c2.css",
"favicon.ico":"favicona9c641bf2b81f0476e876f7c5e375969.ico","my_image.png":
"my_image-231a680f23887d9dd70710ea5efd3c62.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 an
<code>Sprockets::Helpers::RailsHelper::AssetPaths::AssetNotPrecompiledError</code>
exception indicating the name of the missing file(s).</p></div><h5 id="far-future-expires-header">4.1.1 Far-future Expires Header</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 "";
break;
}
</pre>
</div>
<h5 id="gzip-compression">4.1.2 GZip Compression</h5><p>When files are precompiled, Sprockets also creates a
<a href="http://en.wikipedia.org/wiki/Gzip">gzipped</a> (.gz) version of your assets. Web
servers are typically configured to use a moderate compression ratio as a
compromise, but since precompilation happens once, Sprockets uses the maximum
compression ratio, thus reducing the size of the data transfer to the minimum.
On the other hand, web servers can be configured to serve compressed content
directly from disk, rather than deflating non-compressed files themselves.</p><p>NGINX is able to do this automatically enabling <code>gzip_static</code>:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
location ~ ^/(assets)/ {
root /path/to/public;
gzip_static on; # to serve pre-gzipped version
expires max;
add_header Cache-Control public;
}
</pre>
</div>
<p>This directive is available if the core module that provides this feature was
compiled with the web server. Ubuntu/Debian packages, even <code>nginx-light</code>, have
the module compiled. Otherwise, you may need to perform a manual compilation:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
./configure --with-http_gzip_static_module
</pre>
</div>
<p>If you're compiling NGINX with Phusion Passenger you'll need to pass that option
when prompted.</p><p>A robust configuration for Apache is possible but tricky; please Google around.
(Or help update this Guide if you have a good configuration example for Apache.)</p><h4 id="local-precompilation">4.2 Local Precompilation</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">4.3 Live Compilation</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 MD5 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 Gemfile:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
group :production do
gem 'therubyracer'
end
</pre>
</div>
<h4 id="cdns">4.4 CDNs</h4><p>If your assets are being served by a CDN, ensure they don't stick around in your
cache forever. This can cause problems. If you use
<code>config.action_controller.perform_caching = true</code>, Rack::Cache will use
<code>Rails.cache</code> to store assets. This can cause your cache to fill up quickly.</p><p>Every cache is different, so evaluate how your CDN handles caching and make sure
that it plays nicely with the pipeline. You may find quirks related to your
specific set up, you may not. The defaults NGINX uses, for example, should give
you no problems when used as an HTTP cache.</p><p>If you want to serve only some assets from your CDN, you can use custom
<code>:host</code> option of <code>asset_url</code> helper, which overwrites value set in
<code>config.action_controller.asset_host</code>.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
asset_url 'image.png', :host => 'http://cdn.example.com'
</pre>
</div>
<h3 id="customizing-the-pipeline">5 Customizing the Pipeline</h3><h4 id="css-compression">5.1 CSS Compression</h4><p>One of the options for compressing CSS is YUI. The <a href="http://yui.github.io/yuicompressor/css.html">YUI CSS
compressor</a> provides
minification.</p><p>The following line enables YUI compression, and requires the <code>yui-compressor</code>
gem.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.assets.css_compressor = :yui
</pre>
</div>
<p>The other option for compressing CSS if you have the sass-rails gem installed is</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.assets.css_compressor = :sass
</pre>
</div>
<h4 id="javascript-compression">5.2 JavaScript Compression</h4><p>Possible options for JavaScript compression are <code>:closure</code>, <code>:uglifier</code> and
<code>:yui</code>. These require the use of the <code>closure-compiler</code>, <code>uglifier</code> or
<code>yui-compressor</code> gems, respectively.</p><p>The default Gemfile includes <a href="https://github.com/lautis/uglifier">uglifier</a>.
This gem wraps <a href="https://github.com/mishoo/UglifyJS">UglifyJS</a> (written for
NodeJS) in Ruby. It compresses your code by removing white space and comments,
shortening local variable names, and performing other micro-optimizations such
as changing <code>if</code> and <code>else</code> statements to ternary operators where possible.</p><p>The following line invokes <code>uglifier</code> for JavaScript compression.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.assets.js_compressor = :uglifier
</pre>
</div>
<div class="note"><p>You will need an <a href="https://github.com/sstephenson/execjs#readme">ExecJS</a>
supported runtime in order to use <code>uglifier</code>. If you are using Mac OS X or
Windows you have a JavaScript runtime installed in your operating system.</p></div><div class="note"><p>The <code>config.assets.compress</code> initialization option is no longer used in
Rails 4 to enable either CSS or JavaScript compression. Setting it will have no
effect on the application. Instead, setting <code>config.assets.css_compressor</code> and
<code>config.assets.js_compressor</code> will control compression of CSS and JavaScript
assets.</p></div><h4 id="using-your-own-compressor">5.3 Using Your Own Compressor</h4><p>The compressor config settings for CSS and JavaScript also take any object.
This object must have a <code>compress</code> method that takes a string as the sole
argument and it must return a string.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Transformer
def compress(string)
do_something_returning_a_string(string)
end
end