rails_test 4.2.0.beta1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (215) hide show
  1. checksums.yaml +7 -0
  2. data/README.md +83 -0
  3. data/guides/CHANGELOG.md +27 -0
  4. data/guides/Rakefile +77 -0
  5. data/guides/assets/images/akshaysurve.jpg +0 -0
  6. data/guides/assets/images/belongs_to.png +0 -0
  7. data/guides/assets/images/book_icon.gif +0 -0
  8. data/guides/assets/images/bullet.gif +0 -0
  9. data/guides/assets/images/chapters_icon.gif +0 -0
  10. data/guides/assets/images/check_bullet.gif +0 -0
  11. data/guides/assets/images/credits_pic_blank.gif +0 -0
  12. data/guides/assets/images/csrf.png +0 -0
  13. data/guides/assets/images/edge_badge.png +0 -0
  14. data/guides/assets/images/favicon.ico +0 -0
  15. data/guides/assets/images/feature_tile.gif +0 -0
  16. data/guides/assets/images/footer_tile.gif +0 -0
  17. data/guides/assets/images/fxn.png +0 -0
  18. data/guides/assets/images/getting_started/article_with_comments.png +0 -0
  19. data/guides/assets/images/getting_started/challenge.png +0 -0
  20. data/guides/assets/images/getting_started/confirm_dialog.png +0 -0
  21. data/guides/assets/images/getting_started/forbidden_attributes_for_new_article.png +0 -0
  22. data/guides/assets/images/getting_started/form_with_errors.png +0 -0
  23. data/guides/assets/images/getting_started/index_action_with_edit_link.png +0 -0
  24. data/guides/assets/images/getting_started/new_article.png +0 -0
  25. data/guides/assets/images/getting_started/rails_welcome.png +0 -0
  26. data/guides/assets/images/getting_started/routing_error_no_controller.png +0 -0
  27. data/guides/assets/images/getting_started/routing_error_no_route_matches.png +0 -0
  28. data/guides/assets/images/getting_started/show_action_for_articles.png +0 -0
  29. data/guides/assets/images/getting_started/template_is_missing_articles_new.png +0 -0
  30. data/guides/assets/images/getting_started/unknown_action_create_for_articles.png +0 -0
  31. data/guides/assets/images/getting_started/unknown_action_new_for_articles.png +0 -0
  32. data/guides/assets/images/grey_bullet.gif +0 -0
  33. data/guides/assets/images/habtm.png +0 -0
  34. data/guides/assets/images/has_many.png +0 -0
  35. data/guides/assets/images/has_many_through.png +0 -0
  36. data/guides/assets/images/has_one.png +0 -0
  37. data/guides/assets/images/has_one_through.png +0 -0
  38. data/guides/assets/images/header_backdrop.png +0 -0
  39. data/guides/assets/images/header_tile.gif +0 -0
  40. data/guides/assets/images/i18n/demo_html_safe.png +0 -0
  41. data/guides/assets/images/i18n/demo_localized_pirate.png +0 -0
  42. data/guides/assets/images/i18n/demo_translated_en.png +0 -0
  43. data/guides/assets/images/i18n/demo_translated_pirate.png +0 -0
  44. data/guides/assets/images/i18n/demo_translation_missing.png +0 -0
  45. data/guides/assets/images/i18n/demo_untranslated.png +0 -0
  46. data/guides/assets/images/icons/README +5 -0
  47. data/guides/assets/images/icons/callouts/1.png +0 -0
  48. data/guides/assets/images/icons/callouts/10.png +0 -0
  49. data/guides/assets/images/icons/callouts/11.png +0 -0
  50. data/guides/assets/images/icons/callouts/12.png +0 -0
  51. data/guides/assets/images/icons/callouts/13.png +0 -0
  52. data/guides/assets/images/icons/callouts/14.png +0 -0
  53. data/guides/assets/images/icons/callouts/15.png +0 -0
  54. data/guides/assets/images/icons/callouts/2.png +0 -0
  55. data/guides/assets/images/icons/callouts/3.png +0 -0
  56. data/guides/assets/images/icons/callouts/4.png +0 -0
  57. data/guides/assets/images/icons/callouts/5.png +0 -0
  58. data/guides/assets/images/icons/callouts/6.png +0 -0
  59. data/guides/assets/images/icons/callouts/7.png +0 -0
  60. data/guides/assets/images/icons/callouts/8.png +0 -0
  61. data/guides/assets/images/icons/callouts/9.png +0 -0
  62. data/guides/assets/images/icons/caution.png +0 -0
  63. data/guides/assets/images/icons/example.png +0 -0
  64. data/guides/assets/images/icons/home.png +0 -0
  65. data/guides/assets/images/icons/important.png +0 -0
  66. data/guides/assets/images/icons/next.png +0 -0
  67. data/guides/assets/images/icons/note.png +0 -0
  68. data/guides/assets/images/icons/prev.png +0 -0
  69. data/guides/assets/images/icons/tip.png +0 -0
  70. data/guides/assets/images/icons/up.png +0 -0
  71. data/guides/assets/images/icons/warning.png +0 -0
  72. data/guides/assets/images/nav_arrow.gif +0 -0
  73. data/guides/assets/images/oscardelben.jpg +0 -0
  74. data/guides/assets/images/polymorphic.png +0 -0
  75. data/guides/assets/images/radar.png +0 -0
  76. data/guides/assets/images/rails4_features.png +0 -0
  77. data/guides/assets/images/rails_guides_kindle_cover.jpg +0 -0
  78. data/guides/assets/images/rails_guides_logo.gif +0 -0
  79. data/guides/assets/images/rails_logo_remix.gif +0 -0
  80. data/guides/assets/images/session_fixation.png +0 -0
  81. data/guides/assets/images/tab_grey.gif +0 -0
  82. data/guides/assets/images/tab_info.gif +0 -0
  83. data/guides/assets/images/tab_note.gif +0 -0
  84. data/guides/assets/images/tab_red.gif +0 -0
  85. data/guides/assets/images/tab_yellow.gif +0 -0
  86. data/guides/assets/images/tab_yellow.png +0 -0
  87. data/guides/assets/images/vijaydev.jpg +0 -0
  88. data/guides/assets/javascripts/guides.js +59 -0
  89. data/guides/assets/javascripts/jquery.min.js +4 -0
  90. data/guides/assets/javascripts/responsive-tables.js +43 -0
  91. data/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js +59 -0
  92. data/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js +75 -0
  93. data/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js +59 -0
  94. data/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js +65 -0
  95. data/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js +100 -0
  96. data/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js +97 -0
  97. data/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js +91 -0
  98. data/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js +55 -0
  99. data/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js +41 -0
  100. data/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js +52 -0
  101. data/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js +67 -0
  102. data/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js +52 -0
  103. data/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js +57 -0
  104. data/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js +58 -0
  105. data/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js +72 -0
  106. data/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js +88 -0
  107. data/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js +33 -0
  108. data/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js +74 -0
  109. data/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js +64 -0
  110. data/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js +55 -0
  111. data/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js +94 -0
  112. data/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js +51 -0
  113. data/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js +66 -0
  114. data/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js +56 -0
  115. data/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js +69 -0
  116. data/guides/assets/javascripts/syntaxhighlighter/shCore.js +17 -0
  117. data/guides/assets/stylesheets/fixes.css +16 -0
  118. data/guides/assets/stylesheets/kindle.css +11 -0
  119. data/guides/assets/stylesheets/main.css +713 -0
  120. data/guides/assets/stylesheets/print.css +52 -0
  121. data/guides/assets/stylesheets/reset.css +43 -0
  122. data/guides/assets/stylesheets/responsive-tables.css +50 -0
  123. data/guides/assets/stylesheets/style.css +13 -0
  124. data/guides/assets/stylesheets/syntaxhighlighter/shCore.css +226 -0
  125. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css +328 -0
  126. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css +331 -0
  127. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css +339 -0
  128. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css +324 -0
  129. data/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +328 -0
  130. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css +324 -0
  131. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css +324 -0
  132. data/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css +324 -0
  133. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css +117 -0
  134. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css +120 -0
  135. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css +128 -0
  136. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css +113 -0
  137. data/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +117 -0
  138. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css +113 -0
  139. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css +113 -0
  140. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css +113 -0
  141. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +116 -0
  142. data/guides/bug_report_templates/action_controller_gem.rb +47 -0
  143. data/guides/bug_report_templates/action_controller_master.rb +56 -0
  144. data/guides/bug_report_templates/active_record_gem.rb +40 -0
  145. data/guides/bug_report_templates/active_record_master.rb +51 -0
  146. data/guides/rails_guides.rb +63 -0
  147. data/guides/rails_guides/generator.rb +248 -0
  148. data/guides/rails_guides/helpers.rb +53 -0
  149. data/guides/rails_guides/indexer.rb +68 -0
  150. data/guides/rails_guides/kindle.rb +119 -0
  151. data/guides/rails_guides/levenshtein.rb +39 -0
  152. data/guides/rails_guides/markdown.rb +167 -0
  153. data/guides/rails_guides/markdown/renderer.rb +82 -0
  154. data/guides/source/2_2_release_notes.md +435 -0
  155. data/guides/source/2_3_release_notes.md +621 -0
  156. data/guides/source/3_0_release_notes.md +611 -0
  157. data/guides/source/3_1_release_notes.md +559 -0
  158. data/guides/source/3_2_release_notes.md +568 -0
  159. data/guides/source/4_0_release_notes.md +279 -0
  160. data/guides/source/4_1_release_notes.md +730 -0
  161. data/guides/source/4_2_release_notes.md +736 -0
  162. data/guides/source/_license.html.erb +2 -0
  163. data/guides/source/_welcome.html.erb +19 -0
  164. data/guides/source/action_controller_overview.md +1247 -0
  165. data/guides/source/action_mailer_basics.md +738 -0
  166. data/guides/source/action_view_overview.md +1621 -0
  167. data/guides/source/active_job_basics.md +285 -0
  168. data/guides/source/active_model_basics.md +223 -0
  169. data/guides/source/active_record_basics.md +374 -0
  170. data/guides/source/active_record_callbacks.md +413 -0
  171. data/guides/source/active_record_migrations.md +1016 -0
  172. data/guides/source/active_record_postgresql.md +438 -0
  173. data/guides/source/active_record_querying.md +1785 -0
  174. data/guides/source/active_record_validations.md +1169 -0
  175. data/guides/source/active_support_core_extensions.md +3924 -0
  176. data/guides/source/active_support_instrumentation.md +497 -0
  177. data/guides/source/api_documentation_guidelines.md +361 -0
  178. data/guides/source/asset_pipeline.md +1361 -0
  179. data/guides/source/association_basics.md +2238 -0
  180. data/guides/source/caching_with_rails.md +379 -0
  181. data/guides/source/command_line.md +634 -0
  182. data/guides/source/configuring.md +1019 -0
  183. data/guides/source/contributing_to_ruby_on_rails.md +607 -0
  184. data/guides/source/credits.html.erb +80 -0
  185. data/guides/source/debugging_rails_applications.md +861 -0
  186. data/guides/source/development_dependencies_install.md +289 -0
  187. data/guides/source/documents.yaml +197 -0
  188. data/guides/source/engines.md +1401 -0
  189. data/guides/source/form_helpers.md +1010 -0
  190. data/guides/source/generators.md +676 -0
  191. data/guides/source/getting_started.md +2085 -0
  192. data/guides/source/i18n.md +1073 -0
  193. data/guides/source/index.html.erb +28 -0
  194. data/guides/source/initialization.md +704 -0
  195. data/guides/source/kindle/copyright.html.erb +1 -0
  196. data/guides/source/kindle/layout.html.erb +27 -0
  197. data/guides/source/kindle/rails_guides.opf.erb +52 -0
  198. data/guides/source/kindle/toc.html.erb +24 -0
  199. data/guides/source/kindle/toc.ncx.erb +64 -0
  200. data/guides/source/kindle/welcome.html.erb +5 -0
  201. data/guides/source/layout.html.erb +143 -0
  202. data/guides/source/layouts_and_rendering.md +1227 -0
  203. data/guides/source/maintenance_policy.md +75 -0
  204. data/guides/source/nested_model_forms.md +228 -0
  205. data/guides/source/plugins.md +444 -0
  206. data/guides/source/rails_application_templates.md +266 -0
  207. data/guides/source/rails_on_rack.md +332 -0
  208. data/guides/source/routing.md +1141 -0
  209. data/guides/source/ruby_on_rails_guides_guidelines.md +126 -0
  210. data/guides/source/security.md +1024 -0
  211. data/guides/source/testing.md +1055 -0
  212. data/guides/source/upgrading_ruby_on_rails.md +1046 -0
  213. data/guides/source/working_with_javascript_in_rails.md +407 -0
  214. data/guides/w3c_validator.rb +97 -0
  215. metadata +404 -0
@@ -0,0 +1,361 @@
1
+ API Documentation Guidelines
2
+ ============================
3
+
4
+ This guide documents the Ruby on Rails API documentation guidelines.
5
+
6
+ After reading this guide, you will know:
7
+
8
+ * How to write effective prose for documentation purposes.
9
+ * Style guidelines for documenting different kinds of Ruby code.
10
+
11
+ --------------------------------------------------------------------------------
12
+
13
+ RDoc
14
+ ----
15
+
16
+ The [Rails API documentation](http://api.rubyonrails.org) is generated with
17
+ [RDoc](http://docs.seattlerb.org/rdoc/).
18
+
19
+ ```bash
20
+ bundle exec rake rdoc
21
+ ```
22
+
23
+ Resulting HTML files can be found in the ./doc/rdoc directory.
24
+
25
+ Please consult the RDoc documentation for help with the
26
+ [markup](http://docs.seattlerb.org/rdoc/RDoc/Markup.html),
27
+ and also take into account these [additional
28
+ directives](http://docs.seattlerb.org/rdoc/RDoc/Parser/Ruby.html).
29
+
30
+ Wording
31
+ -------
32
+
33
+ Write simple, declarative sentences. Brevity is a plus: get to the point.
34
+
35
+ Write in present tense: "Returns a hash that...", rather than "Returned a hash that..." or "Will return a hash that...".
36
+
37
+ Start comments in upper case. Follow regular punctuation rules:
38
+
39
+ ```ruby
40
+ # Declares an attribute reader backed by an internally-named
41
+ # instance variable.
42
+ def attr_internal_reader(*attrs)
43
+ ...
44
+ end
45
+ ```
46
+
47
+ Communicate to the reader the current way of doing things, both explicitly and implicitly. Use the idioms recommended in edge. Reorder sections to emphasize favored approaches if needed, etc. The documentation should be a model for best practices and canonical, modern Rails usage.
48
+
49
+ Documentation has to be concise but comprehensive. Explore and document edge cases. What happens if a module is anonymous? What if a collection is empty? What if an argument is nil?
50
+
51
+ The proper names of Rails components have a space in between the words, like "Active Support". `ActiveRecord` is a Ruby module, whereas Active Record is an ORM. All Rails documentation should consistently refer to Rails components by their proper name, and if in your next blog post or presentation you remember this tidbit and take it into account that'd be phenomenal.
52
+
53
+ Spell names correctly: Arel, Test::Unit, RSpec, HTML, MySQL, JavaScript, ERB. When in doubt, please have a look at some authoritative source like their official documentation.
54
+
55
+ Use the article "an" for "SQL", as in "an SQL statement". Also "an SQLite database".
56
+
57
+ Prefer wordings that avoid "you"s and "your"s. For example, instead of
58
+
59
+ ```markdown
60
+ If you need to use `return` statements in your callbacks, it is recommended that you explicitly define them as methods.
61
+ ```
62
+
63
+ use this style:
64
+
65
+ ```markdown
66
+ If `return` is needed it is recommended to explicitly define a method.
67
+ ```
68
+
69
+ That said, when using pronouns in reference to a hypothetical person, such as "a
70
+ user with a session cookie", gender neutral pronouns (they/their/them) should be
71
+ used. Instead of:
72
+
73
+ * he or she... use they.
74
+ * him or her... use them.
75
+ * his or her... use their.
76
+ * his or hers... use theirs.
77
+ * himself or herself... use themselves.
78
+
79
+ English
80
+ -------
81
+
82
+ Please use American English (*color*, *center*, *modularize*, etc). See [a list of American and British English spelling differences here](http://en.wikipedia.org/wiki/American_and_British_English_spelling_differences).
83
+
84
+ Example Code
85
+ ------------
86
+
87
+ Choose meaningful examples that depict and cover the basics as well as interesting points or gotchas.
88
+
89
+ Use two spaces to indent chunks of code--that is, for markup purposes, two spaces with respect to the left margin. The examples themselves should use [Rails coding conventions](contributing_to_ruby_on_rails.html#follow-the-coding-conventions).
90
+
91
+ Short docs do not need an explicit "Examples" label to introduce snippets; they just follow paragraphs:
92
+
93
+ ```ruby
94
+ # Converts a collection of elements into a formatted string by
95
+ # calling +to_s+ on all elements and joining them.
96
+ #
97
+ # Blog.all.to_formatted_s # => "First PostSecond PostThird Post"
98
+ ```
99
+
100
+ On the other hand, big chunks of structured documentation may have a separate "Examples" section:
101
+
102
+ ```ruby
103
+ # ==== Examples
104
+ #
105
+ # Person.exists?(5)
106
+ # Person.exists?('5')
107
+ # Person.exists?(name: "David")
108
+ # Person.exists?(['name LIKE ?', "%#{query}%"])
109
+ ```
110
+
111
+ The results of expressions follow them and are introduced by "# => ", vertically aligned:
112
+
113
+ ```ruby
114
+ # For checking if a fixnum is even or odd.
115
+ #
116
+ # 1.even? # => false
117
+ # 1.odd? # => true
118
+ # 2.even? # => true
119
+ # 2.odd? # => false
120
+ ```
121
+
122
+ If a line is too long, the comment may be placed on the next line:
123
+
124
+ ```ruby
125
+ # label(:article, :title)
126
+ # # => <label for="article_title">Title</label>
127
+ #
128
+ # label(:article, :title, "A short title")
129
+ # # => <label for="article_title">A short title</label>
130
+ #
131
+ # label(:article, :title, "A short title", class: "title_label")
132
+ # # => <label for="article_title" class="title_label">A short title</label>
133
+ ```
134
+
135
+ Avoid using any printing methods like `puts` or `p` for that purpose.
136
+
137
+ On the other hand, regular comments do not use an arrow:
138
+
139
+ ```ruby
140
+ # polymorphic_url(record) # same as comment_url(record)
141
+ ```
142
+
143
+ Booleans
144
+ --------
145
+
146
+ In predicates and flags prefer documenting boolean semantics over exact values.
147
+
148
+ When "true" or "false" are used as defined in Ruby use regular font. The
149
+ singletons `true` and `false` need fixed-width font. Please avoid terms like
150
+ "truthy", Ruby defines what is true and false in the language, and thus those
151
+ words have a technical meaning and need no substitutes.
152
+
153
+ As a rule of thumb, do not document singletons unless absolutely necessary. That
154
+ prevents artificial constructs like `!!` or ternaries, allows refactors, and the
155
+ code does not need to rely on the exact values returned by methods being called
156
+ in the implementation.
157
+
158
+ For example:
159
+
160
+ ```markdown
161
+ `config.action_mailer.perform_deliveries` specifies whether mail will actually be delivered and is true by default
162
+ ```
163
+
164
+ the user does not need to know which is the actual default value of the flag,
165
+ and so we only document its boolean semantics.
166
+
167
+ An example with a predicate:
168
+
169
+ ```ruby
170
+ # Returns true if the collection is empty.
171
+ #
172
+ # If the collection has been loaded
173
+ # it is equivalent to <tt>collection.size.zero?</tt>. If the
174
+ # collection has not been loaded, it is equivalent to
175
+ # <tt>collection.exists?</tt>. If the collection has not already been
176
+ # loaded and you are going to fetch the records anyway it is better to
177
+ # check <tt>collection.length.zero?</tt>.
178
+ def empty?
179
+ if loaded?
180
+ size.zero?
181
+ else
182
+ @target.blank? && !scope.exists?
183
+ end
184
+ end
185
+ ```
186
+
187
+ The API is careful not to commit to any particular value, the method has
188
+ predicate semantics, that's enough.
189
+
190
+ File Names
191
+ ----------
192
+
193
+ As a rule of thumb, use filenames relative to the application root:
194
+
195
+ ```
196
+ config/routes.rb # YES
197
+ routes.rb # NO
198
+ RAILS_ROOT/config/routes.rb # NO
199
+ ```
200
+
201
+ Fonts
202
+ -----
203
+
204
+ ### Fixed-width Font
205
+
206
+ Use fixed-width fonts for:
207
+
208
+ * Constants, in particular class and module names.
209
+ * Method names.
210
+ * Literals like `nil`, `false`, `true`, `self`.
211
+ * Symbols.
212
+ * Method parameters.
213
+ * File names.
214
+
215
+ ```ruby
216
+ class Array
217
+ # Calls +to_param+ on all its elements and joins the result with
218
+ # slashes. This is used by +url_for+ in Action Pack.
219
+ def to_param
220
+ collect { |e| e.to_param }.join '/'
221
+ end
222
+ end
223
+ ```
224
+
225
+ WARNING: Using `+...+` for fixed-width font only works with simple content like
226
+ ordinary method names, symbols, paths (with forward slashes), etc. Please use
227
+ `<tt>...</tt>` for everything else, notably class or module names with a
228
+ namespace as in `<tt>ActiveRecord::Base</tt>`.
229
+
230
+ You can quickly test the RDoc output with the following command:
231
+
232
+ ```
233
+ $ echo "+:to_param+" | rdoc --pipe
234
+ #=> <p><code>:to_param</code></p>
235
+ ```
236
+
237
+ ### Regular Font
238
+
239
+ When "true" and "false" are English words rather than Ruby keywords use a regular font:
240
+
241
+ ```ruby
242
+ # Runs all the validations within the specified context.
243
+ # Returns true if no errors are found, false otherwise.
244
+ #
245
+ # If the argument is false (default is +nil+), the context is
246
+ # set to <tt>:create</tt> if <tt>new_record?</tt> is true,
247
+ # and to <tt>:update</tt> if it is not.
248
+ #
249
+ # Validations with no <tt>:on</tt> option will run no
250
+ # matter the context. Validations with # some <tt>:on</tt>
251
+ # option will only run in the specified context.
252
+ def valid?(context = nil)
253
+ ...
254
+ end
255
+ ```
256
+
257
+ Description Lists
258
+ -----------------
259
+
260
+ In lists of options, parameters, etc. use a hyphen between the item and its description (reads better than a colon because normally options are symbols):
261
+
262
+ ```ruby
263
+ # * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
264
+ ```
265
+
266
+ The description starts in upper case and ends with a full stop-it's standard English.
267
+
268
+ Dynamically Generated Methods
269
+ -----------------------------
270
+
271
+ Methods created with `(module|class)_eval(STRING)` have a comment by their side with an instance of the generated code. That comment is 2 spaces away from the template:
272
+
273
+ ```ruby
274
+ for severity in Severity.constants
275
+ class_eval <<-EOT, __FILE__, __LINE__
276
+ def #{severity.downcase}(message = nil, progname = nil, &block) # def debug(message = nil, progname = nil, &block)
277
+ add(#{severity}, message, progname, &block) # add(DEBUG, message, progname, &block)
278
+ end # end
279
+ #
280
+ def #{severity.downcase}? # def debug?
281
+ #{severity} >= @level # DEBUG >= @level
282
+ end # end
283
+ EOT
284
+ end
285
+ ```
286
+
287
+ If the resulting lines are too wide, say 200 columns or more, put the comment above the call:
288
+
289
+ ```ruby
290
+ # def self.find_by_login_and_activated(*args)
291
+ # options = args.extract_options!
292
+ # ...
293
+ # end
294
+ self.class_eval %{
295
+ def self.#{method_id}(*args)
296
+ options = args.extract_options!
297
+ ...
298
+ end
299
+ }
300
+ ```
301
+
302
+ Method Visibility
303
+ -----------------
304
+
305
+ When writing documentation for Rails, it's important to understand the difference between public user-facing API vs internal API.
306
+
307
+ Rails, like most libraries, uses the private keyword from Ruby for defining internal API. However, public API follows a slightly different convention. Instead of assuming all public methods are designed for user consumption, Rails uses the `:nodoc:` directive to annotate these kinds of methods as internal API.
308
+
309
+ This means that there are methods in Rails with `public` visibility that aren't meant for user consumption.
310
+
311
+ An example of this is `ActiveRecord::Core::ClassMethods#arel_table`:
312
+
313
+ ```ruby
314
+ module ActiveRecord::Core::ClassMethods
315
+ def arel_table #:nodoc:
316
+ # do some magic..
317
+ end
318
+ end
319
+ ```
320
+
321
+ If you thought, "this method looks like a public class method for `ActiveRecord::Core`", you were right. But actually the Rails team doesn't want users to rely on this method. So they mark it as `:nodoc:` and it's removed from public documentation. The reasoning behind this is to allow the team to change these methods according to their internal needs across releases as they see fit. The name of this method could change, or the return value, or this entire class may disappear; there's no guarantee and so you shouldn't depend on this API in your plugins or applications. Otherwise, you risk your app or gem breaking when you upgrade to a newer release of Rails.
322
+
323
+ As a contributor, it's important to think about whether this API is meant for end-user consumption. The Rails team is committed to not making any breaking changes to public API across releases without going through a full deprecation cycle. It's recommended that you `:nodoc:` any of your internal methods/classes unless they're already private (meaning visibility), in which case it's internal by default. Once the API stabilizes the visibility can change, but changing public API is much harder due to backwards compatibility.
324
+
325
+ A class or module is marked with `:nodoc:` to indicate that all methods are internal API and should never be used directly.
326
+
327
+ If you come across an existing `:nodoc:` you should tread lightly. Consider asking someone from the core team or author of the code before removing it. This should almost always happen through a pull request instead of the docrails project.
328
+
329
+ A `:nodoc:` should never be added simply because a method or class is missing documentation. There may be an instance where an internal public method wasn't given a `:nodoc:` by mistake, for example when switching a method from private to public visibility. When this happens it should be discussed over a PR on a case-by-case basis and never committed directly to docrails.
330
+
331
+ To summarize, the Rails team uses `:nodoc:` to mark publicly visible methods and classes for internal use; changes to the visibility of API should be considered carefully and discussed over a pull request first.
332
+
333
+ Regarding the Rails Stack
334
+ -------------------------
335
+
336
+ When documenting parts of Rails API, it's important to remember all of the
337
+ pieces that go into the Rails stack.
338
+
339
+ This means that behavior may change depending on the scope or context of the
340
+ method or class you're trying to document.
341
+
342
+ In various places there is different behavior when you take the entire stack
343
+ into account, one such example is
344
+ `ActionView::Helpers::AssetTagHelper#image_tag`:
345
+
346
+ ```ruby
347
+ # image_tag("icon.png")
348
+ # # => <img alt="Icon" src="/assets/icon.png" />
349
+ ```
350
+
351
+ Although the default behavior for `#image_tag` is to always return
352
+ `/images/icon.png`, we take into account the full Rails stack (including the
353
+ Asset Pipeline) we may see the result seen above.
354
+
355
+ We're only concerned with the behavior experienced when using the full default
356
+ Rails stack.
357
+
358
+ In this case, we want to document the behavior of the _framework_, and not just
359
+ this specific method.
360
+
361
+ If you have a question on how the Rails team handles certain API, don't hesitate to open a ticket or send a patch to the [issue tracker](https://github.com/rails/rails/issues).
@@ -0,0 +1,1361 @@
1
+ The Asset Pipeline
2
+ ==================
3
+
4
+ This guide covers the asset pipeline.
5
+
6
+ After reading this guide, you will know:
7
+
8
+ * What the asset pipeline is and what it does.
9
+ * How to properly organize your application assets.
10
+ * The benefits of the asset pipeline.
11
+ * How to add a pre-processor to the pipeline.
12
+ * How to package assets with a gem.
13
+
14
+ --------------------------------------------------------------------------------
15
+
16
+ What is the Asset Pipeline?
17
+ ---------------------------
18
+
19
+ The asset pipeline provides a framework to concatenate and minify or compress
20
+ JavaScript and CSS assets. It also adds the ability to write these assets in
21
+ other languages and pre-processors such as CoffeeScript, Sass and ERB.
22
+
23
+ The asset pipeline is technically no longer a core feature of Rails 4, it has
24
+ been extracted out of the framework into the
25
+ [sprockets-rails](https://github.com/rails/sprockets-rails) gem.
26
+
27
+ The asset pipeline is enabled by default.
28
+
29
+ You can disable the asset pipeline while creating a new application by
30
+ passing the `--skip-sprockets` option.
31
+
32
+ ```bash
33
+ rails new appname --skip-sprockets
34
+ ```
35
+
36
+ Rails 4 automatically adds the `sass-rails`, `coffee-rails` and `uglifier`
37
+ gems to your Gemfile, which are used by Sprockets for asset compression:
38
+
39
+ ```ruby
40
+ gem 'sass-rails'
41
+ gem 'uglifier'
42
+ gem 'coffee-rails'
43
+ ```
44
+
45
+ Using the `--skip-sprockets` option will prevent Rails 4 from adding
46
+ `sass-rails` and `uglifier` to Gemfile, so if you later want to enable
47
+ the asset pipeline you will have to add those gems to your Gemfile. Also,
48
+ creating an application with the `--skip-sprockets` option will generate
49
+ a slightly different `config/application.rb` file, with a require statement
50
+ for the sprockets railtie that is commented-out. You will have to remove
51
+ the comment operator on that line to later enable the asset pipeline:
52
+
53
+ ```ruby
54
+ # require "sprockets/railtie"
55
+ ```
56
+
57
+ To set asset compression methods, set the appropriate configuration options
58
+ in `production.rb` - `config.assets.css_compressor` for your CSS and
59
+ `config.assets.js_compressor` for your JavaScript:
60
+
61
+ ```ruby
62
+ config.assets.css_compressor = :yui
63
+ config.assets.js_compressor = :uglifier
64
+ ```
65
+
66
+ NOTE: The `sass-rails` gem is automatically used for CSS compression if included
67
+ in Gemfile and no `config.assets.css_compressor` option is set.
68
+
69
+
70
+ ### Main Features
71
+
72
+ The first feature of the pipeline is to concatenate assets, which can reduce the
73
+ number of requests that a browser makes to render a web page. Web browsers are
74
+ limited in the number of requests that they can make in parallel, so fewer
75
+ requests can mean faster loading for your application.
76
+
77
+ Sprockets concatenates all JavaScript files into one master `.js` file and all
78
+ CSS files into one master `.css` file. As you'll learn later in this guide, you
79
+ can customize this strategy to group files any way you like. In production,
80
+ Rails inserts an MD5 fingerprint into each filename so that the file is cached
81
+ by the web browser. You can invalidate the cache by altering this fingerprint,
82
+ which happens automatically whenever you change the file contents.
83
+
84
+ The second feature of the asset pipeline is asset minification or compression.
85
+ For CSS files, this is done by removing whitespace and comments. For JavaScript,
86
+ more complex processes can be applied. You can choose from a set of built in
87
+ options or specify your own.
88
+
89
+ The third feature of the asset pipeline is it allows coding assets via a
90
+ higher-level language, with precompilation down to the actual assets. Supported
91
+ languages include Sass for CSS, CoffeeScript for JavaScript, and ERB for both by
92
+ default.
93
+
94
+ ### What is Fingerprinting and Why Should I Care?
95
+
96
+ Fingerprinting is a technique that makes the name of a file dependent on the
97
+ contents of the file. When the file contents change, the filename is also
98
+ changed. For content that is static or infrequently changed, this provides an
99
+ easy way to tell whether two versions of a file are identical, even across
100
+ different servers or deployment dates.
101
+
102
+ When a filename is unique and based on its content, HTTP headers can be set to
103
+ encourage caches everywhere (whether at CDNs, at ISPs, in networking equipment,
104
+ or in web browsers) to keep their own copy of the content. When the content is
105
+ updated, the fingerprint will change. This will cause the remote clients to
106
+ request a new copy of the content. This is generally known as _cache busting_.
107
+
108
+ The technique sprockets uses for fingerprinting is to insert a hash of the
109
+ content into the name, usually at the end. For example a CSS file `global.css`
110
+
111
+ ```
112
+ global-908e25f4bf641868d8683022a5b62f54.css
113
+ ```
114
+
115
+ This is the strategy adopted by the Rails asset pipeline.
116
+
117
+ Rails' old strategy was to append a date-based query string to every asset linked
118
+ with a built-in helper. In the source the generated code looked like this:
119
+
120
+ ```
121
+ /stylesheets/global.css?1309495796
122
+ ```
123
+
124
+ The query string strategy has several disadvantages:
125
+
126
+ 1. **Not all caches will reliably cache content where the filename only differs by
127
+ query parameters**
128
+
129
+ [Steve Souders recommends](http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/),
130
+ "...avoiding a querystring for cacheable resources". He found that in this
131
+ case 5-20% of requests will not be cached. Query strings in particular do not
132
+ work at all with some CDNs for cache invalidation.
133
+
134
+ 2. **The file name can change between nodes in multi-server environments.**
135
+
136
+ The default query string in Rails 2.x is based on the modification time of
137
+ the files. When assets are deployed to a cluster, there is no guarantee that the
138
+ timestamps will be the same, resulting in different values being used depending
139
+ on which server handles the request.
140
+
141
+ 3. **Too much cache invalidation**
142
+
143
+ When static assets are deployed with each new release of code, the mtime
144
+ (time of last modification) of _all_ these files changes, forcing all remote
145
+ clients to fetch them again, even when the content of those assets has not changed.
146
+
147
+ Fingerprinting fixes these problems by avoiding query strings, and by ensuring
148
+ that filenames are consistent based on their content.
149
+
150
+ Fingerprinting is enabled by default for production and disabled for all other
151
+ environments. You can enable or disable it in your configuration through the
152
+ `config.assets.digest` option.
153
+
154
+ More reading:
155
+
156
+ * [Optimize caching](http://code.google.com/speed/page-speed/docs/caching.html)
157
+ * [Revving Filenames: don't use querystring](http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/)
158
+
159
+
160
+ How to Use the Asset Pipeline
161
+ -----------------------------
162
+
163
+ In previous versions of Rails, all assets were located in subdirectories of
164
+ `public` such as `images`, `javascripts` and `stylesheets`. With the asset
165
+ pipeline, the preferred location for these assets is now the `app/assets`
166
+ directory. Files in this directory are served by the Sprockets middleware.
167
+
168
+ Assets can still be placed in the `public` hierarchy. Any assets under `public`
169
+ will be served as static files by the application or web server when
170
+ `config.serve_static_assets` is set to true. You should use
171
+ `app/assets` for files that must undergo some pre-processing before they are
172
+ served.
173
+
174
+ In production, Rails precompiles these files to `public/assets` by default. The
175
+ precompiled copies are then served as static assets by the web server. The files
176
+ in `app/assets` are never served directly in production.
177
+
178
+ ### Controller Specific Assets
179
+
180
+ When you generate a scaffold or a controller, Rails also generates a JavaScript
181
+ file (or CoffeeScript file if the `coffee-rails` gem is in the `Gemfile`) and a
182
+ Cascading Style Sheet file (or SCSS file if `sass-rails` is in the `Gemfile`)
183
+ for that controller. Additionally, when generating a scaffold, Rails generates
184
+ the file scaffolds.css (or scaffolds.css.scss if `sass-rails` is in the
185
+ `Gemfile`.)
186
+
187
+ For example, if you generate a `ProjectsController`, Rails will also add a new
188
+ file at `app/assets/javascripts/projects.js.coffee` and another at
189
+ `app/assets/stylesheets/projects.css.scss`. By default these files will be ready
190
+ to use by your application immediately using the `require_tree` directive. See
191
+ [Manifest Files and Directives](#manifest-files-and-directives) for more details
192
+ on require_tree.
193
+
194
+ You can also opt to include controller specific stylesheets and JavaScript files
195
+ only in their respective controllers using the following:
196
+
197
+ `<%= javascript_include_tag params[:controller] %>` or `<%= stylesheet_link_tag
198
+ params[:controller] %>`
199
+
200
+ When doing this, ensure you are not using the `require_tree` directive, as that
201
+ will result in your assets being included more than once.
202
+
203
+ WARNING: When using asset precompilation, you will need to ensure that your
204
+ controller assets will be precompiled when loading them on a per page basis. By
205
+ default .coffee and .scss files will not be precompiled on their own. See
206
+ [Precompiling Assets](#precompiling-assets) for more information on how
207
+ precompiling works.
208
+
209
+ NOTE: You must have an ExecJS supported runtime in order to use CoffeeScript.
210
+ If you are using Mac OS X or Windows, you have a JavaScript runtime installed in
211
+ your operating system. Check
212
+ [ExecJS](https://github.com/sstephenson/execjs#readme) documentation to know all
213
+ supported JavaScript runtimes.
214
+
215
+ You can also disable generation of controller specific asset files by adding the
216
+ following to your `config/application.rb` configuration:
217
+
218
+ ```ruby
219
+ config.generators do |g|
220
+ g.assets false
221
+ end
222
+ ```
223
+
224
+ ### Asset Organization
225
+
226
+ Pipeline assets can be placed inside an application in one of three locations:
227
+ `app/assets`, `lib/assets` or `vendor/assets`.
228
+
229
+ * `app/assets` is for assets that are owned by the application, such as custom
230
+ images, JavaScript files or stylesheets.
231
+
232
+ * `lib/assets` is for your own libraries' code that doesn't really fit into the
233
+ scope of the application or those libraries which are shared across applications.
234
+
235
+ * `vendor/assets` is for assets that are owned by outside entities, such as
236
+ code for JavaScript plugins and CSS frameworks.
237
+
238
+ WARNING: If you are upgrading from Rails 3, please take into account that assets
239
+ under `lib/assets` or `vendor/assets` are available for inclusion via the
240
+ application manifests but no longer part of the precompile array. See
241
+ [Precompiling Assets](#precompiling-assets) for guidance.
242
+
243
+ #### Search Paths
244
+
245
+ When a file is referenced from a manifest or a helper, Sprockets searches the
246
+ three default asset locations for it.
247
+
248
+ The default locations are: the `images`, `javascripts` and `stylesheets`
249
+ directories under the `app/assets` folder, but these subdirectories
250
+ are not special - any path under `assets/*` will be searched.
251
+
252
+ For example, these files:
253
+
254
+ ```
255
+ app/assets/javascripts/home.js
256
+ lib/assets/javascripts/moovinator.js
257
+ vendor/assets/javascripts/slider.js
258
+ vendor/assets/somepackage/phonebox.js
259
+ ```
260
+
261
+ would be referenced in a manifest like this:
262
+
263
+ ```js
264
+ //= require home
265
+ //= require moovinator
266
+ //= require slider
267
+ //= require phonebox
268
+ ```
269
+
270
+ Assets inside subdirectories can also be accessed.
271
+
272
+ ```
273
+ app/assets/javascripts/sub/something.js
274
+ ```
275
+
276
+ is referenced as:
277
+
278
+ ```js
279
+ //= require sub/something
280
+ ```
281
+
282
+ You can view the search path by inspecting
283
+ `Rails.application.config.assets.paths` in the Rails console.
284
+
285
+ Besides the standard `assets/*` paths, additional (fully qualified) paths can be
286
+ added to the pipeline in `config/application.rb`. For example:
287
+
288
+ ```ruby
289
+ config.assets.paths << Rails.root.join("lib", "videoplayer", "flash")
290
+ ```
291
+
292
+ Paths are traversed in the order they occur in the search path. By default,
293
+ this means the files in `app/assets` take precedence, and will mask
294
+ corresponding paths in `lib` and `vendor`.
295
+
296
+ It is important to note that files you want to reference outside a manifest must
297
+ be added to the precompile array or they will not be available in the production
298
+ environment.
299
+
300
+ #### Using Index Files
301
+
302
+ Sprockets uses files named `index` (with the relevant extensions) for a special
303
+ purpose.
304
+
305
+ For example, if you have a jQuery library with many modules, which is stored in
306
+ `lib/assets/javascripts/library_name`, the file `lib/assets/javascripts/library_name/index.js` serves as
307
+ the manifest for all files in this library. This file could include a list of
308
+ all the required files in order, or a simple `require_tree` directive.
309
+
310
+ The library as a whole can be accessed in the application manifest like so:
311
+
312
+ ```js
313
+ //= require library_name
314
+ ```
315
+
316
+ This simplifies maintenance and keeps things clean by allowing related code to
317
+ be grouped before inclusion elsewhere.
318
+
319
+ ### Coding Links to Assets
320
+
321
+ Sprockets does not add any new methods to access your assets - you still use the
322
+ familiar `javascript_include_tag` and `stylesheet_link_tag`:
323
+
324
+ ```erb
325
+ <%= stylesheet_link_tag "application", media: "all" %>
326
+ <%= javascript_include_tag "application" %>
327
+ ```
328
+
329
+ If using the turbolinks gem, which is included by default in Rails 4, then
330
+ include the 'data-turbolinks-track' option which causes turbolinks to check if
331
+ an asset has been updated and if so loads it into the page:
332
+
333
+ ```erb
334
+ <%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
335
+ <%= javascript_include_tag "application", "data-turbolinks-track" => true %>
336
+ ```
337
+
338
+ In regular views you can access images in the `public/assets/images` directory
339
+ like this:
340
+
341
+ ```erb
342
+ <%= image_tag "rails.png" %>
343
+ ```
344
+
345
+ Provided that the pipeline is enabled within your application (and not disabled
346
+ in the current environment context), this file is served by Sprockets. If a file
347
+ exists at `public/assets/rails.png` it is served by the web server.
348
+
349
+ Alternatively, a request for a file with an MD5 hash such as
350
+ `public/assets/rails-af27b6a414e6da00003503148be9b409.png` is treated the same
351
+ way. How these hashes are generated is covered in the [In
352
+ Production](#in-production) section later on in this guide.
353
+
354
+ Sprockets will also look through the paths specified in `config.assets.paths`,
355
+ which includes the standard application paths and any paths added by Rails
356
+ engines.
357
+
358
+ Images can also be organized into subdirectories if required, and then can be
359
+ accessed by specifying the directory's name in the tag:
360
+
361
+ ```erb
362
+ <%= image_tag "icons/rails.png" %>
363
+ ```
364
+
365
+ WARNING: If you're precompiling your assets (see [In Production](#in-production)
366
+ below), linking to an asset that does not exist will raise an exception in the
367
+ calling page. This includes linking to a blank string. As such, be careful using
368
+ `image_tag` and the other helpers with user-supplied data.
369
+
370
+ #### CSS and ERB
371
+
372
+ The asset pipeline automatically evaluates ERB. This means if you add an
373
+ `erb` extension to a CSS asset (for example, `application.css.erb`), then
374
+ helpers like `asset_path` are available in your CSS rules:
375
+
376
+ ```css
377
+ .class { background-image: url(<%= asset_path 'image.png' %>) }
378
+ ```
379
+
380
+ This writes the path to the particular asset being referenced. In this example,
381
+ it would make sense to have an image in one of the asset load paths, such as
382
+ `app/assets/images/image.png`, which would be referenced here. If this image is
383
+ already available in `public/assets` as a fingerprinted file, then that path is
384
+ referenced.
385
+
386
+ If you want to use a [data URI](http://en.wikipedia.org/wiki/Data_URI_scheme) -
387
+ a method of embedding the image data directly into the CSS file - you can use
388
+ the `asset_data_uri` helper.
389
+
390
+ ```css
391
+ #logo { background: url(<%= asset_data_uri 'logo.png' %>) }
392
+ ```
393
+
394
+ This inserts a correctly-formatted data URI into the CSS source.
395
+
396
+ Note that the closing tag cannot be of the style `-%>`.
397
+
398
+ #### CSS and Sass
399
+
400
+ When using the asset pipeline, paths to assets must be re-written and
401
+ `sass-rails` provides `-url` and `-path` helpers (hyphenated in Sass,
402
+ underscored in Ruby) for the following asset classes: image, font, video, audio,
403
+ JavaScript and stylesheet.
404
+
405
+ * `image-url("rails.png")` becomes `url(/assets/rails.png)`
406
+ * `image-path("rails.png")` becomes `"/assets/rails.png"`.
407
+
408
+ The more generic form can also be used:
409
+
410
+ * `asset-url("rails.png")` becomes `url(/assets/rails.png)`
411
+ * `asset-path("rails.png")` becomes `"/assets/rails.png"`
412
+
413
+ #### JavaScript/CoffeeScript and ERB
414
+
415
+ If you add an `erb` extension to a JavaScript asset, making it something such as
416
+ `application.js.erb`, you can then use the `asset_path` helper in your
417
+ JavaScript code:
418
+
419
+ ```js
420
+ $('#logo').attr({ src: "<%= asset_path('logo.png') %>" });
421
+ ```
422
+
423
+ This writes the path to the particular asset being referenced.
424
+
425
+ Similarly, you can use the `asset_path` helper in CoffeeScript files with `erb`
426
+ extension (e.g., `application.js.coffee.erb`):
427
+
428
+ ```js
429
+ $('#logo').attr src: "<%= asset_path('logo.png') %>"
430
+ ```
431
+
432
+ ### Manifest Files and Directives
433
+
434
+ Sprockets uses manifest files to determine which assets to include and serve.
435
+ These manifest files contain _directives_ - instructions that tell Sprockets
436
+ which files to require in order to build a single CSS or JavaScript file. With
437
+ these directives, Sprockets loads the files specified, processes them if
438
+ necessary, concatenates them into one single file and then compresses them (if
439
+ `Rails.application.config.assets.compress` is true). By serving one file rather
440
+ than many, the load time of pages can be greatly reduced because the browser
441
+ makes fewer requests. Compression also reduces file size, enabling the
442
+ browser to download them faster.
443
+
444
+
445
+ For example, a new Rails 4 application includes a default
446
+ `app/assets/javascripts/application.js` file containing the following lines:
447
+
448
+ ```js
449
+ // ...
450
+ //= require jquery
451
+ //= require jquery_ujs
452
+ //= require_tree .
453
+ ```
454
+
455
+ In JavaScript files, Sprockets directives begin with `//=`. In the above case,
456
+ the file is using the `require` and the `require_tree` directives. The `require`
457
+ directive is used to tell Sprockets the files you wish to require. Here, you are
458
+ requiring the files `jquery.js` and `jquery_ujs.js` that are available somewhere
459
+ in the search path for Sprockets. You need not supply the extensions explicitly.
460
+ Sprockets assumes you are requiring a `.js` file when done from within a `.js`
461
+ file.
462
+
463
+ The `require_tree` directive tells Sprockets to recursively include _all_
464
+ JavaScript files in the specified directory into the output. These paths must be
465
+ specified relative to the manifest file. You can also use the
466
+ `require_directory` directive which includes all JavaScript files only in the
467
+ directory specified, without recursion.
468
+
469
+ Directives are processed top to bottom, but the order in which files are
470
+ included by `require_tree` is unspecified. You should not rely on any particular
471
+ order among those. If you need to ensure some particular JavaScript ends up
472
+ above some other in the concatenated file, require the prerequisite file first
473
+ in the manifest. Note that the family of `require` directives prevents files
474
+ from being included twice in the output.
475
+
476
+ Rails also creates a default `app/assets/stylesheets/application.css` file
477
+ which contains these lines:
478
+
479
+ ```css
480
+ /* ...
481
+ *= require_self
482
+ *= require_tree .
483
+ */
484
+ ```
485
+
486
+ Rails 4 creates both `app/assets/javascripts/application.js` and
487
+ `app/assets/stylesheets/application.css` regardless of whether the
488
+ --skip-sprockets option is used when creating a new rails application. This is
489
+ so you can easily add asset pipelining later if you like.
490
+
491
+ The directives that work in JavaScript files also work in stylesheets
492
+ (though obviously including stylesheets rather than JavaScript files). The
493
+ `require_tree` directive in a CSS manifest works the same way as the JavaScript
494
+ one, requiring all stylesheets from the current directory.
495
+
496
+ In this example, `require_self` is used. This puts the CSS contained within the
497
+ file (if any) at the precise location of the `require_self` call.
498
+
499
+ NOTE. If you want to use multiple Sass files, you should generally use the [Sass `@import` rule](http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#import)
500
+ instead of these Sprockets directives. When using Sprockets directives, Sass files exist within
501
+ their own scope, making variables or mixins only available within the document they were defined in.
502
+
503
+ You can do file globbing as well using `@import "*"`, and `@import "**/*"` to add the whole tree which is equivalent to how `require_tree` works. Check the [sass-rails documentation](https://github.com/rails/sass-rails#features) for more info and important caveats.
504
+
505
+ You can have as many manifest files as you need. For example, the `admin.css`
506
+ and `admin.js` manifest could contain the JS and CSS files that are used for the
507
+ admin section of an application.
508
+
509
+ The same remarks about ordering made above apply. In particular, you can specify
510
+ individual files and they are compiled in the order specified. For example, you
511
+ might concatenate three CSS files together this way:
512
+
513
+ ```js
514
+ /* ...
515
+ *= require reset
516
+ *= require layout
517
+ *= require chrome
518
+ */
519
+ ```
520
+
521
+ ### Preprocessing
522
+
523
+ The file extensions used on an asset determine what preprocessing is applied.
524
+ When a controller or a scaffold is generated with the default Rails gemset, a
525
+ CoffeeScript file and a SCSS file are generated in place of a regular JavaScript
526
+ and CSS file. The example used before was a controller called "projects", which
527
+ generated an `app/assets/javascripts/projects.js.coffee` and an
528
+ `app/assets/stylesheets/projects.css.scss` file.
529
+
530
+ In development mode, or if the asset pipeline is disabled, when these files are
531
+ requested they are processed by the processors provided by the `coffee-script`
532
+ and `sass` gems and then sent back to the browser as JavaScript and CSS
533
+ respectively. When asset pipelining is enabled, these files are preprocessed and
534
+ placed in the `public/assets` directory for serving by either the Rails app or
535
+ web server.
536
+
537
+ Additional layers of preprocessing can be requested by adding other extensions,
538
+ where each extension is processed in a right-to-left manner. These should be
539
+ used in the order the processing should be applied. For example, a stylesheet
540
+ called `app/assets/stylesheets/projects.css.scss.erb` is first processed as ERB,
541
+ then SCSS, and finally served as CSS. The same applies to a JavaScript file -
542
+ `app/assets/javascripts/projects.js.coffee.erb` is processed as ERB, then
543
+ CoffeeScript, and served as JavaScript.
544
+
545
+ Keep in mind the order of these preprocessors is important. For example, if
546
+ you called your JavaScript file `app/assets/javascripts/projects.js.erb.coffee`
547
+ then it would be processed with the CoffeeScript interpreter first, which
548
+ wouldn't understand ERB and therefore you would run into problems.
549
+
550
+
551
+ In Development
552
+ --------------
553
+
554
+ In development mode, assets are served as separate files in the order they are
555
+ specified in the manifest file.
556
+
557
+ This manifest `app/assets/javascripts/application.js`:
558
+
559
+ ```js
560
+ //= require core
561
+ //= require projects
562
+ //= require tickets
563
+ ```
564
+
565
+ would generate this HTML:
566
+
567
+ ```html
568
+ <script src="/assets/core.js?body=1"></script>
569
+ <script src="/assets/projects.js?body=1"></script>
570
+ <script src="/assets/tickets.js?body=1"></script>
571
+ ```
572
+
573
+ The `body` param is required by Sprockets.
574
+
575
+ ### Runtime Error Checking
576
+
577
+ By default the asset pipeline will check for potential errors in development mode during
578
+ runtime. To disable this behavior you can set:
579
+
580
+ ```ruby
581
+ config.assets.raise_runtime_errors = false
582
+ ```
583
+
584
+ When this option is true, the asset pipeline will check if all the assets loaded
585
+ in your application are included in the `config.assets.precompile` list.
586
+ If `config.assets.digest` is also true, the asset pipeline will require that
587
+ all requests for assets include digests.
588
+
589
+ ### Turning Digests Off
590
+
591
+ You can turn off digests by updating `config/environments/development.rb` to
592
+ include:
593
+
594
+ ```ruby
595
+ config.assets.digest = false
596
+ ```
597
+
598
+ When this option is true, digests will be generated for asset URLs.
599
+
600
+ ### Turning Debugging Off
601
+
602
+ You can turn off debug mode by updating `config/environments/development.rb` to
603
+ include:
604
+
605
+ ```ruby
606
+ config.assets.debug = false
607
+ ```
608
+
609
+ When debug mode is off, Sprockets concatenates and runs the necessary
610
+ preprocessors on all files. With debug mode turned off the manifest above would
611
+ generate instead:
612
+
613
+ ```html
614
+ <script src="/assets/application.js"></script>
615
+ ```
616
+
617
+ Assets are compiled and cached on the first request after the server is started.
618
+ Sprockets sets a `must-revalidate` Cache-Control HTTP header to reduce request
619
+ overhead on subsequent requests - on these the browser gets a 304 (Not Modified)
620
+ response.
621
+
622
+ If any of the files in the manifest have changed between requests, the server
623
+ responds with a new compiled file.
624
+
625
+ Debug mode can also be enabled in Rails helper methods:
626
+
627
+ ```erb
628
+ <%= stylesheet_link_tag "application", debug: true %>
629
+ <%= javascript_include_tag "application", debug: true %>
630
+ ```
631
+
632
+ The `:debug` option is redundant if debug mode is already on.
633
+
634
+ You can also enable compression in development mode as a sanity check, and
635
+ disable it on-demand as required for debugging.
636
+
637
+ In Production
638
+ -------------
639
+
640
+ In the production environment Sprockets uses the fingerprinting scheme outlined
641
+ above. By default Rails assumes assets have been precompiled and will be
642
+ served as static assets by your web server.
643
+
644
+ During the precompilation phase an MD5 is generated from the contents of the
645
+ compiled files, and inserted into the filenames as they are written to disc.
646
+ These fingerprinted names are used by the Rails helpers in place of the manifest
647
+ name.
648
+
649
+ For example this:
650
+
651
+ ```erb
652
+ <%= javascript_include_tag "application" %>
653
+ <%= stylesheet_link_tag "application" %>
654
+ ```
655
+
656
+ generates something like this:
657
+
658
+ ```html
659
+ <script src="/assets/application-908e25f4bf641868d8683022a5b62f54.js"></script>
660
+ <link href="/assets/application-4dd5b109ee3439da54f5bdfd78a80473.css" media="screen"
661
+ rel="stylesheet" />
662
+ ```
663
+
664
+ Note: with the Asset Pipeline the :cache and :concat options aren't used
665
+ anymore, delete these options from the `javascript_include_tag` and
666
+ `stylesheet_link_tag`.
667
+
668
+ The fingerprinting behavior is controlled by the `config.assets.digest`
669
+ initialization option (which defaults to `true` for production and `false` for
670
+ everything else).
671
+
672
+ NOTE: Under normal circumstances the default `config.assets.digest` option
673
+ should not be changed. If there are no digests in the filenames, and far-future
674
+ headers are set, remote clients will never know to refetch the files when their
675
+ content changes.
676
+
677
+ ### Precompiling Assets
678
+
679
+ Rails comes bundled with a rake task to compile the asset manifests and other
680
+ files in the pipeline.
681
+
682
+ Compiled assets are written to the location specified in `config.assets.prefix`.
683
+ By default, this is the `/assets` directory.
684
+
685
+ You can call this task on the server during deployment to create compiled
686
+ versions of your assets directly on the server. See the next section for
687
+ information on compiling locally.
688
+
689
+ The rake task is:
690
+
691
+ ```bash
692
+ $ RAILS_ENV=production bin/rake assets:precompile
693
+ ```
694
+
695
+ Capistrano (v2.15.1 and above) includes a recipe to handle this in deployment.
696
+ Add the following line to `Capfile`:
697
+
698
+ ```ruby
699
+ load 'deploy/assets'
700
+ ```
701
+
702
+ This links the folder specified in `config.assets.prefix` to `shared/assets`.
703
+ If you already use this shared folder you'll need to write your own deployment
704
+ task.
705
+
706
+ It is important that this folder is shared between deployments so that remotely
707
+ cached pages referencing the old compiled assets still work for the life of
708
+ the cached page.
709
+
710
+ The default matcher for compiling files includes `application.js`,
711
+ `application.css` and all non-JS/CSS files (this will include all image assets
712
+ automatically) from `app/assets` folders including your gems:
713
+
714
+ ```ruby
715
+ [ Proc.new { |filename, path| path =~ /app\/assets/ && !%w(.js .css).include?(File.extname(filename)) },
716
+ /application.(css|js)$/ ]
717
+ ```
718
+
719
+ NOTE: The matcher (and other members of the precompile array; see below) is
720
+ applied to final compiled file names. This means anything that compiles to
721
+ JS/CSS is excluded, as well as raw JS/CSS files; for example, `.coffee` and
722
+ `.scss` files are **not** automatically included as they compile to JS/CSS.
723
+
724
+ If you have other manifests or individual stylesheets and JavaScript files to
725
+ include, you can add them to the `precompile` array in `config/initializers/assets.rb`:
726
+
727
+ ```ruby
728
+ Rails.application.config.assets.precompile += ['admin.js', 'admin.css', 'swfObject.js']
729
+ ```
730
+
731
+ Or, you can opt to precompile all assets with something like this:
732
+
733
+ ```ruby
734
+ # config/initializers/assets.rb
735
+ Rails.application.config.assets.precompile << Proc.new do |path|
736
+ if path =~ /\.(css|js)\z/
737
+ full_path = Rails.application.assets.resolve(path).to_path
738
+ app_assets_path = Rails.root.join('app', 'assets').to_path
739
+ if full_path.starts_with? app_assets_path
740
+ puts "including asset: " + full_path
741
+ true
742
+ else
743
+ puts "excluding asset: " + full_path
744
+ false
745
+ end
746
+ else
747
+ false
748
+ end
749
+ end
750
+ ```
751
+
752
+ NOTE. Always specify an expected compiled filename that ends with .js or .css,
753
+ even if you want to add Sass or CoffeeScript files to the precompile array.
754
+
755
+ The rake task also generates a `manifest-md5hash.json` that contains a list with
756
+ all your assets and their respective fingerprints. This is used by the Rails
757
+ helper methods to avoid handing the mapping requests back to Sprockets. A
758
+ typical manifest file looks like:
759
+
760
+ ```ruby
761
+ {"files":{"application-723d1be6cc741a3aabb1cec24276d681.js":{"logical_path":"application.js","mtime":"2013-07-26T22:55:03-07:00","size":302506,
762
+ "digest":"723d1be6cc741a3aabb1cec24276d681"},"application-12b3c7dd74d2e9df37e7cbb1efa76a6d.css":{"logical_path":"application.css","mtime":"2013-07-26T22:54:54-07:00","size":1560,
763
+ "digest":"12b3c7dd74d2e9df37e7cbb1efa76a6d"},"application-1c5752789588ac18d7e1a50b1f0fd4c2.css":{"logical_path":"application.css","mtime":"2013-07-26T22:56:17-07:00","size":1591,
764
+ "digest":"1c5752789588ac18d7e1a50b1f0fd4c2"},"favicon-a9c641bf2b81f0476e876f7c5e375969.ico":{"logical_path":"favicon.ico","mtime":"2013-07-26T23:00:10-07:00","size":1406,
765
+ "digest":"a9c641bf2b81f0476e876f7c5e375969"},"my_image-231a680f23887d9dd70710ea5efd3c62.png":{"logical_path":"my_image.png","mtime":"2013-07-26T23:00:27-07:00","size":6646,
766
+ "digest":"231a680f23887d9dd70710ea5efd3c62"}},"assets":{"application.js":
767
+ "application-723d1be6cc741a3aabb1cec24276d681.js","application.css":
768
+ "application-1c5752789588ac18d7e1a50b1f0fd4c2.css",
769
+ "favicon.ico":"favicona9c641bf2b81f0476e876f7c5e375969.ico","my_image.png":
770
+ "my_image-231a680f23887d9dd70710ea5efd3c62.png"}}
771
+ ```
772
+
773
+ The default location for the manifest is the root of the location specified in
774
+ `config.assets.prefix` ('/assets' by default).
775
+
776
+ NOTE: If there are missing precompiled files in production you will get an
777
+ `Sprockets::Helpers::RailsHelper::AssetPaths::AssetNotPrecompiledError`
778
+ exception indicating the name of the missing file(s).
779
+
780
+ #### Far-future Expires Header
781
+
782
+ Precompiled assets exist on the file system and are served directly by your web
783
+ server. They do not have far-future headers by default, so to get the benefit of
784
+ fingerprinting you'll have to update your server configuration to add those
785
+ headers.
786
+
787
+ For Apache:
788
+
789
+ ```apache
790
+ # The Expires* directives requires the Apache module
791
+ # `mod_expires` to be enabled.
792
+ <Location /assets/>
793
+ # Use of ETag is discouraged when Last-Modified is present
794
+ Header unset ETag
795
+ FileETag None
796
+ # RFC says only cache for 1 year
797
+ ExpiresActive On
798
+ ExpiresDefault "access plus 1 year"
799
+ </Location>
800
+ ```
801
+
802
+ For NGINX:
803
+
804
+ ```nginx
805
+ location ~ ^/assets/ {
806
+ expires 1y;
807
+ add_header Cache-Control public;
808
+
809
+ add_header ETag "";
810
+ break;
811
+ }
812
+ ```
813
+
814
+ #### GZip Compression
815
+
816
+ When files are precompiled, Sprockets also creates a
817
+ [gzipped](http://en.wikipedia.org/wiki/Gzip) (.gz) version of your assets. Web
818
+ servers are typically configured to use a moderate compression ratio as a
819
+ compromise, but since precompilation happens once, Sprockets uses the maximum
820
+ compression ratio, thus reducing the size of the data transfer to the minimum.
821
+ On the other hand, web servers can be configured to serve compressed content
822
+ directly from disk, rather than deflating non-compressed files themselves.
823
+
824
+ NGINX is able to do this automatically enabling `gzip_static`:
825
+
826
+ ```nginx
827
+ location ~ ^/(assets)/ {
828
+ root /path/to/public;
829
+ gzip_static on; # to serve pre-gzipped version
830
+ expires max;
831
+ add_header Cache-Control public;
832
+ }
833
+ ```
834
+
835
+ This directive is available if the core module that provides this feature was
836
+ compiled with the web server. Ubuntu/Debian packages, even `nginx-light`, have
837
+ the module compiled. Otherwise, you may need to perform a manual compilation:
838
+
839
+ ```bash
840
+ ./configure --with-http_gzip_static_module
841
+ ```
842
+
843
+ If you're compiling NGINX with Phusion Passenger you'll need to pass that option
844
+ when prompted.
845
+
846
+ A robust configuration for Apache is possible but tricky; please Google around.
847
+ (Or help update this Guide if you have a good configuration example for Apache.)
848
+
849
+ ### Local Precompilation
850
+
851
+ There are several reasons why you might want to precompile your assets locally.
852
+ Among them are:
853
+
854
+ * You may not have write access to your production file system.
855
+ * You may be deploying to more than one server, and want to avoid
856
+ duplication of work.
857
+ * You may be doing frequent deploys that do not include asset changes.
858
+
859
+ Local compilation allows you to commit the compiled files into source control,
860
+ and deploy as normal.
861
+
862
+ There are three caveats:
863
+
864
+ * You must not run the Capistrano deployment task that precompiles assets.
865
+ * You must ensure any necessary compressors or minifiers are
866
+ available on your development system.
867
+ * You must change the following application configuration setting:
868
+
869
+ In `config/environments/development.rb`, place the following line:
870
+
871
+ ```ruby
872
+ config.assets.prefix = "/dev-assets"
873
+ ```
874
+
875
+ The `prefix` change makes Sprockets use a different URL for serving assets in
876
+ development mode, and pass all requests to Sprockets. The prefix is still set to
877
+ `/assets` in the production environment. Without this change, the application
878
+ would serve the precompiled assets from `/assets` in development, and you would
879
+ not see any local changes until you compile assets again.
880
+
881
+ In practice, this will allow you to precompile locally, have those files in your
882
+ working tree, and commit those files to source control when needed. Development
883
+ mode will work as expected.
884
+
885
+ ### Live Compilation
886
+
887
+ In some circumstances you may wish to use live compilation. In this mode all
888
+ requests for assets in the pipeline are handled by Sprockets directly.
889
+
890
+ To enable this option set:
891
+
892
+ ```ruby
893
+ config.assets.compile = true
894
+ ```
895
+
896
+ On the first request the assets are compiled and cached as outlined in
897
+ development above, and the manifest names used in the helpers are altered to
898
+ include the MD5 hash.
899
+
900
+ Sprockets also sets the `Cache-Control` HTTP header to `max-age=31536000`. This
901
+ signals all caches between your server and the client browser that this content
902
+ (the file served) can be cached for 1 year. The effect of this is to reduce the
903
+ number of requests for this asset from your server; the asset has a good chance
904
+ of being in the local browser cache or some intermediate cache.
905
+
906
+ This mode uses more memory, performs more poorly than the default and is not
907
+ recommended.
908
+
909
+ If you are deploying a production application to a system without any
910
+ pre-existing JavaScript runtimes, you may want to add one to your Gemfile:
911
+
912
+ ```ruby
913
+ group :production do
914
+ gem 'therubyracer'
915
+ end
916
+ ```
917
+
918
+ ### CDNs
919
+
920
+ CDN stands for [Content Delivery
921
+ Network](http://en.wikipedia.org/wiki/Content_delivery_network), they are
922
+ primarily designed to cache assets all over the world so that when a browser
923
+ requests the asset, a cached copy will be geographically close to that browser.
924
+ If you are serving assets directly from your Rails server in production, the
925
+ best practice is to use a CDN in front of your application.
926
+
927
+ A common pattern for using a CDN is to set your production application as the
928
+ "origin" server. This means when a browser requests an asset from the CDN and
929
+ there is a cache miss, it will grab the file from your server on the fly and
930
+ then cache it. For example if you are running a Rails application on
931
+ `example.com` and have a CDN configured at `mycdnsubdomain.fictional-cdn.com`,
932
+ then when a request is made to `mycdnsubdomain.fictional-
933
+ cdn.com/assets/smile.png`, the CDN will query your server once at
934
+ `example.com/assets/smile.png` and cache the request. The next request to the
935
+ CDN that comes in to the same URL will hit the cached copy. When the CDN can
936
+ serve an asset directly the request never touches your Rails server. Since the
937
+ assets from a CDN are geographically closer to the browser, the request is
938
+ faster, and since your server doesn't need to spend time serving assets, it can
939
+ focus on serving application code as fast as possible.
940
+
941
+ #### Set up a CDN to Serve Static Assets
942
+
943
+ To set up your CDN you have to have your application running in production on
944
+ the internet at a publically available URL, for example `example.com`. Next
945
+ you'll need to sign up for a CDN service from a cloud hosting provider. When you
946
+ do this you need to configure the "origin" of the CDN to point back at your
947
+ website `example.com`, check your provider for documentation on configuring the
948
+ origin server.
949
+
950
+ The CDN you provisioned should give you a custom subdomain for your application
951
+ such as `mycdnsubdomain.fictional-cdn.com` (note fictional-cdn.com is not a
952
+ valid CDN provider at the time of this writing). Now that you have configured
953
+ your CDN server, you need to tell browsers to use your CDN to grab assets
954
+ instead of your Rails server directly. You can do this by configuring Rails to
955
+ set your CDN as the asset host instead of using a relative path. To set your
956
+ asset host in Rails, you need to set `config.action_controller.asset_host` in
957
+ `config/production.rb`:
958
+
959
+ ```ruby
960
+ config.action_controller.asset_host = 'mycdnsubdomain.fictional-cdn.com'
961
+ ```
962
+
963
+ NOTE: You only need to provide the "host", this is the subdomain and root
964
+ domain, you do not need to specify a protocol or "scheme" such as `http://` or
965
+ `https://`. When a web page is requested, the protocol in the link to your asset
966
+ that is generated will match how the webpage is accessed by default.
967
+
968
+ You can also set this value through an [environment
969
+ variable](http://en.wikipedia.org/wiki/Environment_variable) to make running a
970
+ staging copy of your site easier:
971
+
972
+ ```
973
+ config.action_controller.asset_host = ENV['CDN_HOST']
974
+ ```
975
+
976
+
977
+
978
+ Note: You would need to set `CDN_HOST` on your server to `mycdnsubdomain
979
+ .fictional-cdn.com` for this to work.
980
+
981
+ Once you have configured your server and your CDN when you serve a webpage that
982
+ has an asset:
983
+
984
+ ```erb
985
+ <%= asset_path('smile.png') %>
986
+ ```
987
+
988
+ Instead of returning a path such as `/assets/smile.png` (digests are left out
989
+ for readability). The URL generated will have the full path to your CDN.
990
+
991
+ ```
992
+ http://mycdnsubdomain.fictional-cdn.com/assets/smile.png
993
+ ```
994
+
995
+ If the CDN has a copy of `smile.png` it will serve it to the browser and your
996
+ server doesn't even know it was requested. If the CDN does not have a copy it
997
+ will try to find it a the "origin" `example.com/assets/smile.png` and then store
998
+ it for future use.
999
+
1000
+ If you want to serve only some assets from your CDN, you can use custom `:host`
1001
+ option your asset helper, which overwrites value set in
1002
+ `config.action_controller.asset_host`.
1003
+
1004
+ ```erb
1005
+ <%= asset_path 'image.png', host: 'mycdnsubdomain.fictional-cdn.com' %>
1006
+ ```
1007
+
1008
+ #### Customize CDN Caching Behavior
1009
+
1010
+ A CDN works by caching content. If the CDN has stale or bad content, then it is
1011
+ hurting rather than helping your application. The purpose of this section is to
1012
+ describe general caching behavior of most CDNs, your specific provider may
1013
+ behave slightly differently.
1014
+
1015
+ ##### CDN Request Caching
1016
+
1017
+ While a CDN is described as being good for caching assets, in reality caches the
1018
+ entire request. This includes the body of the asset as well as any headers. The
1019
+ most important one being `Cache-Control` which tells the CDN (and web browsers)
1020
+ how to cache contents. This means that if someone requests an asset that does
1021
+ not exist `/assets/i-dont-exist.png` and your Rails application returns a 404,
1022
+ then your CDN will likely cache the 404 page if a valid `Cache-Control` header
1023
+ is present.
1024
+
1025
+ ##### CDN Header Debugging
1026
+
1027
+ One way to check the headers are cached properly in your CDN is by using [curl](
1028
+ http://explainshell.com/explain?cmd=curl+-I+http%3A%2F%2Fwww.example.com). You
1029
+ can request the headers from both your server and your CDN to verify they are
1030
+ the same:
1031
+
1032
+ ```
1033
+ $ curl -I http://www.example/assets/application-
1034
+ d0e099e021c95eb0de3615fd1d8c4d83.css
1035
+ HTTP/1.1 200 OK
1036
+ Server: Cowboy
1037
+ Date: Sun, 24 Aug 2014 20:27:50 GMT
1038
+ Connection: keep-alive
1039
+ Last-Modified: Thu, 08 May 2014 01:24:14 GMT
1040
+ Content-Type: text/css
1041
+ Cache-Control: public, max-age=2592000
1042
+ Content-Length: 126560
1043
+ Via: 1.1 vegur
1044
+ ```
1045
+
1046
+ Versus the CDN copy.
1047
+
1048
+ ```
1049
+ $ curl -I http://mycdnsubdomain.fictional-cdn.com/application-
1050
+ d0e099e021c95eb0de3615fd1d8c4d83.css
1051
+ HTTP/1.1 200 OK Server: Cowboy Last-
1052
+ Modified: Thu, 08 May 2014 01:24:14 GMT Content-Type: text/css
1053
+ Cache-Control:
1054
+ public, max-age=2592000
1055
+ Via: 1.1 vegur
1056
+ Content-Length: 126560
1057
+ Accept-Ranges:
1058
+ bytes
1059
+ Date: Sun, 24 Aug 2014 20:28:45 GMT
1060
+ Via: 1.1 varnish
1061
+ Age: 885814
1062
+ Connection: keep-alive
1063
+ X-Served-By: cache-dfw1828-DFW
1064
+ X-Cache: HIT
1065
+ X-Cache-Hits:
1066
+ 68
1067
+ X-Timer: S1408912125.211638212,VS0,VE0
1068
+ ```
1069
+
1070
+ Check your CDN documentation for any additional information they may provide
1071
+ such as `X-Cache` or for any additional headers they may add.
1072
+
1073
+ ##### CDNs and the Cache-Control Header
1074
+
1075
+ The [cache control
1076
+ header](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9) is a W3C
1077
+ specification that describes how a request can be cached. When no CDN is used, a
1078
+ browser will use this information to cache contents. This is very helpful for
1079
+ assets that are not modified so that a browser does not need to re-download a
1080
+ website's CSS or javascript on every request. Generally we want our Rails server
1081
+ to tell our CDN (and browser) that the asset is "public", that means any cache
1082
+ can store the request. Also we commonly want to set `max-age` which is how long
1083
+ the cache will store the object before invalidating the cache. The `max-age`
1084
+ value is set to seconds with a maximum possible value of `31536000` which is one
1085
+ year. You can do this in your rails application by setting
1086
+
1087
+ ```
1088
+ config.static_cache_control = "public, max-age=31536000"
1089
+ ```
1090
+
1091
+ Now when your application serves an asset in production, the CDN will store the
1092
+ asset for up to a year. Since most CDNs also cache headers of the request, this
1093
+ `Cache-Control` will be passed along to all future browsers seeking this asset,
1094
+ the browser then knows that it can store this asset for a very long time before
1095
+ needing to re-request it.
1096
+
1097
+ ##### CDNs and URL based Cache Invalidation
1098
+
1099
+ Most CDNs will cache contents of an asset based on the complete URL. This means
1100
+ that a request to
1101
+
1102
+ ```
1103
+ http://mycdnsubdomain.fictional-cdn.com/assets/smile-123.png
1104
+ ```
1105
+
1106
+ Will be a completely different cache from
1107
+
1108
+ ```
1109
+ http://mycdnsubdomain.fictional-cdn.com/assets/smile.png
1110
+ ```
1111
+
1112
+ If you want to set far future `max-age` in your `Cache-Control` (and you do),
1113
+ then make sure when you change your assets that your cache is invalidated. For
1114
+ example when changing the smiley face in an image from yellow to blue, you want
1115
+ all visitors of your site to get the new blue face. When using a CDN with the
1116
+ Rails asset pipeline `config.assets.digest` is set to true by default so that
1117
+ each asset will have a different file name when it is changed. This way you
1118
+ don't have to ever manually invalidate any items in your cache. By using a
1119
+ different unique asset name instead, your users get the latest asset.
1120
+
1121
+ Customizing the Pipeline
1122
+ ------------------------
1123
+
1124
+ ### CSS Compression
1125
+
1126
+ One of the options for compressing CSS is YUI. The [YUI CSS
1127
+ compressor](http://yui.github.io/yuicompressor/css.html) provides
1128
+ minification.
1129
+
1130
+ The following line enables YUI compression, and requires the `yui-compressor`
1131
+ gem.
1132
+
1133
+ ```ruby
1134
+ config.assets.css_compressor = :yui
1135
+ ```
1136
+ The other option for compressing CSS if you have the sass-rails gem installed is
1137
+
1138
+ ```ruby
1139
+ config.assets.css_compressor = :sass
1140
+ ```
1141
+
1142
+ ### JavaScript Compression
1143
+
1144
+ Possible options for JavaScript compression are `:closure`, `:uglifier` and
1145
+ `:yui`. These require the use of the `closure-compiler`, `uglifier` or
1146
+ `yui-compressor` gems, respectively.
1147
+
1148
+ The default Gemfile includes [uglifier](https://github.com/lautis/uglifier).
1149
+ This gem wraps [UglifyJS](https://github.com/mishoo/UglifyJS) (written for
1150
+ NodeJS) in Ruby. It compresses your code by removing white space and comments,
1151
+ shortening local variable names, and performing other micro-optimizations such
1152
+ as changing `if` and `else` statements to ternary operators where possible.
1153
+
1154
+ The following line invokes `uglifier` for JavaScript compression.
1155
+
1156
+ ```ruby
1157
+ config.assets.js_compressor = :uglifier
1158
+ ```
1159
+
1160
+ NOTE: You will need an [ExecJS](https://github.com/sstephenson/execjs#readme)
1161
+ supported runtime in order to use `uglifier`. If you are using Mac OS X or
1162
+ Windows you have a JavaScript runtime installed in your operating system.
1163
+
1164
+ NOTE: The `config.assets.compress` initialization option is no longer used in
1165
+ Rails 4 to enable either CSS or JavaScript compression. Setting it will have no
1166
+ effect on the application. Instead, setting `config.assets.css_compressor` and
1167
+ `config.assets.js_compressor` will control compression of CSS and JavaScript
1168
+ assets.
1169
+
1170
+ ### Using Your Own Compressor
1171
+
1172
+ The compressor config settings for CSS and JavaScript also take any object.
1173
+ This object must have a `compress` method that takes a string as the sole
1174
+ argument and it must return a string.
1175
+
1176
+ ```ruby
1177
+ class Transformer
1178
+ def compress(string)
1179
+ do_something_returning_a_string(string)
1180
+ end
1181
+ end
1182
+ ```
1183
+
1184
+ To enable this, pass a new object to the config option in `application.rb`:
1185
+
1186
+ ```ruby
1187
+ config.assets.css_compressor = Transformer.new
1188
+ ```
1189
+
1190
+
1191
+ ### Changing the _assets_ Path
1192
+
1193
+ The public path that Sprockets uses by default is `/assets`.
1194
+
1195
+ This can be changed to something else:
1196
+
1197
+ ```ruby
1198
+ config.assets.prefix = "/some_other_path"
1199
+ ```
1200
+
1201
+ This is a handy option if you are updating an older project that didn't use the
1202
+ asset pipeline and already uses this path or you wish to use this path for
1203
+ a new resource.
1204
+
1205
+ ### X-Sendfile Headers
1206
+
1207
+ The X-Sendfile header is a directive to the web server to ignore the response
1208
+ from the application, and instead serve a specified file from disk. This option
1209
+ is off by default, but can be enabled if your server supports it. When enabled,
1210
+ this passes responsibility for serving the file to the web server, which is
1211
+ faster. Have a look at [send_file](http://api.rubyonrails.org/classes/ActionController/DataStreaming.html#method-i-send_file)
1212
+ on how to use this feature.
1213
+
1214
+ Apache and NGINX support this option, which can be enabled in
1215
+ `config/environments/production.rb`:
1216
+
1217
+ ```ruby
1218
+ # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for Apache
1219
+ # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
1220
+ ```
1221
+
1222
+ WARNING: If you are upgrading an existing application and intend to use this
1223
+ option, take care to paste this configuration option only into `production.rb`
1224
+ and any other environments you define with production behavior (not
1225
+ `application.rb`).
1226
+
1227
+ TIP: For further details have a look at the docs of your production web server:
1228
+ - [Apache](https://tn123.org/mod_xsendfile/)
1229
+ - [NGINX](http://wiki.nginx.org/XSendfile)
1230
+
1231
+ Assets Cache Store
1232
+ ------------------
1233
+
1234
+ The default Rails cache store will be used by Sprockets to cache assets in
1235
+ development and production. This can be changed by setting
1236
+ `config.assets.cache_store`:
1237
+
1238
+ ```ruby
1239
+ config.assets.cache_store = :memory_store
1240
+ ```
1241
+
1242
+ The options accepted by the assets cache store are the same as the application's
1243
+ cache store.
1244
+
1245
+ ```ruby
1246
+ config.assets.cache_store = :memory_store, { size: 32.megabytes }
1247
+ ```
1248
+
1249
+ To disable the assets cache store:
1250
+
1251
+ ```ruby
1252
+ config.assets.configure do |env|
1253
+ env.cache = ActiveSupport::Cache.lookup_store(:null_store)
1254
+ end
1255
+ ```
1256
+
1257
+ Adding Assets to Your Gems
1258
+ --------------------------
1259
+
1260
+ Assets can also come from external sources in the form of gems.
1261
+
1262
+ A good example of this is the `jquery-rails` gem which comes with Rails as the
1263
+ standard JavaScript library gem. This gem contains an engine class which
1264
+ inherits from `Rails::Engine`. By doing this, Rails is informed that the
1265
+ directory for this gem may contain assets and the `app/assets`, `lib/assets` and
1266
+ `vendor/assets` directories of this engine are added to the search path of
1267
+ Sprockets.
1268
+
1269
+ Making Your Library or Gem a Pre-Processor
1270
+ ------------------------------------------
1271
+
1272
+ As Sprockets uses [Tilt](https://github.com/rtomayko/tilt) as a generic
1273
+ interface to different templating engines, your gem should just implement the
1274
+ Tilt template protocol. Normally, you would subclass `Tilt::Template` and
1275
+ reimplement the `prepare` method, which initializes your template, and the
1276
+ `evaluate` method, which returns the processed source. The original source is
1277
+ stored in `data`. Have a look at
1278
+ [`Tilt::Template`](https://github.com/rtomayko/tilt/blob/master/lib/tilt/template.rb)
1279
+ sources to learn more.
1280
+
1281
+ ```ruby
1282
+ module BangBang
1283
+ class Template < ::Tilt::Template
1284
+ def prepare
1285
+ # Do any initialization here
1286
+ end
1287
+
1288
+ # Adds a "!" to original template.
1289
+ def evaluate(scope, locals, &block)
1290
+ "#{data}!"
1291
+ end
1292
+ end
1293
+ end
1294
+ ```
1295
+
1296
+ Now that you have a `Template` class, it's time to associate it with an
1297
+ extension for template files:
1298
+
1299
+ ```ruby
1300
+ Sprockets.register_engine '.bang', BangBang::Template
1301
+ ```
1302
+
1303
+ Upgrading from Old Versions of Rails
1304
+ ------------------------------------
1305
+
1306
+ There are a few issues when upgrading from Rails 3.0 or Rails 2.x. The first is
1307
+ moving the files from `public/` to the new locations. See [Asset
1308
+ Organization](#asset-organization) above for guidance on the correct locations
1309
+ for different file types.
1310
+
1311
+ Next will be avoiding duplicate JavaScript files. Since jQuery is the default
1312
+ JavaScript library from Rails 3.1 onwards, you don't need to copy `jquery.js`
1313
+ into `app/assets` and it will be included automatically.
1314
+
1315
+ The third is updating the various environment files with the correct default
1316
+ options.
1317
+
1318
+ In `application.rb`:
1319
+
1320
+ ```ruby
1321
+ # Version of your assets, change this if you want to expire all your assets
1322
+ config.assets.version = '1.0'
1323
+
1324
+ # Change the path that assets are served from config.assets.prefix = "/assets"
1325
+ ```
1326
+
1327
+ In `development.rb`:
1328
+
1329
+ ```ruby
1330
+ # Expands the lines which load the assets
1331
+ config.assets.debug = true
1332
+ ```
1333
+
1334
+ And in `production.rb`:
1335
+
1336
+ ```ruby
1337
+ # Choose the compressors to use (if any) config.assets.js_compressor =
1338
+ # :uglifier config.assets.css_compressor = :yui
1339
+
1340
+ # Don't fallback to assets pipeline if a precompiled asset is missed
1341
+ config.assets.compile = false
1342
+
1343
+ # Generate digests for assets URLs. This is planned for deprecation.
1344
+ config.assets.digest = true
1345
+
1346
+ # Precompile additional assets (application.js, application.css, and all
1347
+ # non-JS/CSS are already added) config.assets.precompile += %w( search.js )
1348
+ ```
1349
+
1350
+ Rails 4 no longer sets default config values for Sprockets in `test.rb`, so
1351
+ `test.rb` now requires Sprockets configuration. The old defaults in the test
1352
+ environment are: `config.assets.compile = true`, `config.assets.compress =
1353
+ false`, `config.assets.debug = false` and `config.assets.digest = false`.
1354
+
1355
+ The following should also be added to `Gemfile`:
1356
+
1357
+ ```ruby
1358
+ gem 'sass-rails', "~> 3.2.3"
1359
+ gem 'coffee-rails', "~> 3.2.1"
1360
+ gem 'uglifier'
1361
+ ```