rails 3.2.22.5 → 4.0.0.beta1

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of rails might be problematic. Click here for more details.

Files changed (281) hide show
  1. checksums.yaml +4 -4
  2. data/README.rdoc +77 -0
  3. data/guides/CHANGELOG.md +9 -0
  4. data/guides/Rakefile +77 -0
  5. data/guides/assets/images/belongs_to.png +0 -0
  6. data/guides/assets/images/book_icon.gif +0 -0
  7. data/guides/assets/images/bullet.gif +0 -0
  8. data/guides/assets/images/challenge.png +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/confirm_dialog.png +0 -0
  19. data/guides/assets/images/getting_started/forbidden_attributes_for_new_post.png +0 -0
  20. data/guides/assets/images/getting_started/form_with_errors.png +0 -0
  21. data/guides/assets/images/getting_started/index_action_with_edit_link.png +0 -0
  22. data/guides/assets/images/getting_started/new_post.png +0 -0
  23. data/guides/assets/images/getting_started/post_with_comments.png +0 -0
  24. data/guides/assets/images/getting_started/routing_error_no_controller.png +0 -0
  25. data/guides/assets/images/getting_started/routing_error_no_route_matches.png +0 -0
  26. data/guides/assets/images/getting_started/show_action_for_posts.png +0 -0
  27. data/guides/assets/images/getting_started/template_is_missing_posts_new.png +0 -0
  28. data/guides/assets/images/getting_started/undefined_method_post_path.png +0 -0
  29. data/guides/assets/images/getting_started/unknown_action_create_for_posts.png +0 -0
  30. data/guides/assets/images/getting_started/unknown_action_new_for_posts.png +0 -0
  31. data/guides/assets/images/grey_bullet.gif +0 -0
  32. data/guides/assets/images/habtm.png +0 -0
  33. data/guides/assets/images/has_many.png +0 -0
  34. data/guides/assets/images/has_many_through.png +0 -0
  35. data/guides/assets/images/has_one.png +0 -0
  36. data/guides/assets/images/has_one_through.png +0 -0
  37. data/guides/assets/images/header_backdrop.png +0 -0
  38. data/guides/assets/images/header_tile.gif +0 -0
  39. data/guides/assets/images/i18n/demo_html_safe.png +0 -0
  40. data/guides/assets/images/i18n/demo_localized_pirate.png +0 -0
  41. data/guides/assets/images/i18n/demo_translated_en.png +0 -0
  42. data/guides/assets/images/i18n/demo_translated_pirate.png +0 -0
  43. data/guides/assets/images/i18n/demo_translation_missing.png +0 -0
  44. data/guides/assets/images/i18n/demo_untranslated.png +0 -0
  45. data/guides/assets/images/icons/README +5 -0
  46. data/guides/assets/images/icons/callouts/1.png +0 -0
  47. data/guides/assets/images/icons/callouts/10.png +0 -0
  48. data/guides/assets/images/icons/callouts/11.png +0 -0
  49. data/guides/assets/images/icons/callouts/12.png +0 -0
  50. data/guides/assets/images/icons/callouts/13.png +0 -0
  51. data/guides/assets/images/icons/callouts/14.png +0 -0
  52. data/guides/assets/images/icons/callouts/15.png +0 -0
  53. data/guides/assets/images/icons/callouts/2.png +0 -0
  54. data/guides/assets/images/icons/callouts/3.png +0 -0
  55. data/guides/assets/images/icons/callouts/4.png +0 -0
  56. data/guides/assets/images/icons/callouts/5.png +0 -0
  57. data/guides/assets/images/icons/callouts/6.png +0 -0
  58. data/guides/assets/images/icons/callouts/7.png +0 -0
  59. data/guides/assets/images/icons/callouts/8.png +0 -0
  60. data/guides/assets/images/icons/callouts/9.png +0 -0
  61. data/guides/assets/images/icons/caution.png +0 -0
  62. data/guides/assets/images/icons/example.png +0 -0
  63. data/guides/assets/images/icons/home.png +0 -0
  64. data/guides/assets/images/icons/important.png +0 -0
  65. data/guides/assets/images/icons/next.png +0 -0
  66. data/guides/assets/images/icons/note.png +0 -0
  67. data/guides/assets/images/icons/prev.png +0 -0
  68. data/guides/assets/images/icons/tip.png +0 -0
  69. data/guides/assets/images/icons/up.png +0 -0
  70. data/guides/assets/images/icons/warning.png +0 -0
  71. data/guides/assets/images/jaimeiniesta.jpg +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/rails_welcome.png +0 -0
  81. data/guides/assets/images/session_fixation.png +0 -0
  82. data/guides/assets/images/tab_grey.gif +0 -0
  83. data/guides/assets/images/tab_info.gif +0 -0
  84. data/guides/assets/images/tab_note.gif +0 -0
  85. data/guides/assets/images/tab_red.gif +0 -0
  86. data/guides/assets/images/tab_yellow.gif +0 -0
  87. data/guides/assets/images/tab_yellow.png +0 -0
  88. data/guides/assets/images/vijaydev.jpg +0 -0
  89. data/guides/assets/javascripts/guides.js +57 -0
  90. data/guides/assets/javascripts/jquery.min.js +4 -0
  91. data/guides/assets/javascripts/responsive-tables.js +43 -0
  92. data/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js +59 -0
  93. data/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js +75 -0
  94. data/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js +59 -0
  95. data/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js +65 -0
  96. data/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js +100 -0
  97. data/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js +97 -0
  98. data/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js +91 -0
  99. data/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js +55 -0
  100. data/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js +41 -0
  101. data/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js +52 -0
  102. data/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js +67 -0
  103. data/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js +52 -0
  104. data/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js +57 -0
  105. data/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js +58 -0
  106. data/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js +72 -0
  107. data/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js +88 -0
  108. data/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js +33 -0
  109. data/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js +74 -0
  110. data/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js +64 -0
  111. data/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js +55 -0
  112. data/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js +94 -0
  113. data/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js +51 -0
  114. data/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js +66 -0
  115. data/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js +56 -0
  116. data/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js +69 -0
  117. data/guides/assets/javascripts/syntaxhighlighter/shCore.js +17 -0
  118. data/guides/assets/stylesheets/fixes.css +16 -0
  119. data/guides/assets/stylesheets/kindle.css +11 -0
  120. data/guides/assets/stylesheets/main.css +709 -0
  121. data/guides/assets/stylesheets/print.css +52 -0
  122. data/guides/assets/stylesheets/reset.css +43 -0
  123. data/guides/assets/stylesheets/responsive-tables.css +50 -0
  124. data/guides/assets/stylesheets/style.css +13 -0
  125. data/guides/assets/stylesheets/syntaxhighlighter/shCore.css +226 -0
  126. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css +328 -0
  127. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css +331 -0
  128. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css +339 -0
  129. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css +324 -0
  130. data/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +328 -0
  131. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css +324 -0
  132. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css +324 -0
  133. data/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css +324 -0
  134. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css +117 -0
  135. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css +120 -0
  136. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css +128 -0
  137. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css +113 -0
  138. data/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +117 -0
  139. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css +113 -0
  140. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css +113 -0
  141. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css +113 -0
  142. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +116 -0
  143. data/guides/code/getting_started/Gemfile +38 -0
  144. data/guides/code/getting_started/Gemfile.lock +150 -0
  145. data/guides/code/getting_started/README.rdoc +28 -0
  146. data/guides/code/getting_started/Rakefile +6 -0
  147. data/guides/code/getting_started/app/assets/images/rails.png +0 -0
  148. data/guides/code/getting_started/app/assets/javascripts/application.js +16 -0
  149. data/guides/code/getting_started/app/assets/javascripts/comments.js.coffee +3 -0
  150. data/guides/code/getting_started/app/assets/javascripts/posts.js.coffee +3 -0
  151. data/guides/code/getting_started/app/assets/javascripts/welcome.js.coffee +3 -0
  152. data/guides/code/getting_started/app/assets/stylesheets/application.css +13 -0
  153. data/guides/code/getting_started/app/assets/stylesheets/comments.css.scss +3 -0
  154. data/guides/code/getting_started/app/assets/stylesheets/posts.css.scss +3 -0
  155. data/guides/code/getting_started/app/assets/stylesheets/welcome.css.scss +3 -0
  156. data/guides/code/getting_started/app/controllers/application_controller.rb +5 -0
  157. data/guides/code/getting_started/app/controllers/comments_controller.rb +17 -0
  158. data/guides/code/getting_started/app/controllers/posts_controller.rb +47 -0
  159. data/guides/code/getting_started/app/controllers/welcome_controller.rb +4 -0
  160. data/guides/code/getting_started/app/helpers/application_helper.rb +2 -0
  161. data/guides/code/getting_started/app/helpers/comments_helper.rb +2 -0
  162. data/guides/code/getting_started/app/helpers/posts_helper.rb +2 -0
  163. data/guides/code/getting_started/app/helpers/welcome_helper.rb +2 -0
  164. data/guides/code/getting_started/app/models/comment.rb +3 -0
  165. data/guides/code/getting_started/app/models/post.rb +7 -0
  166. data/guides/code/getting_started/app/views/comments/_comment.html.erb +15 -0
  167. data/guides/code/getting_started/app/views/comments/_form.html.erb +13 -0
  168. data/guides/code/getting_started/app/views/layouts/application.html.erb +14 -0
  169. data/guides/code/getting_started/app/views/posts/_form.html.erb +27 -0
  170. data/guides/code/getting_started/app/views/posts/edit.html.erb +5 -0
  171. data/guides/code/getting_started/app/views/posts/index.html.erb +21 -0
  172. data/guides/code/getting_started/app/views/posts/new.html.erb +5 -0
  173. data/guides/code/getting_started/app/views/posts/show.html.erb +18 -0
  174. data/guides/code/getting_started/app/views/welcome/index.html.erb +3 -0
  175. data/guides/code/getting_started/bin/bundle +4 -0
  176. data/guides/code/getting_started/bin/rails +4 -0
  177. data/guides/code/getting_started/bin/rake +4 -0
  178. data/guides/code/getting_started/config.ru +4 -0
  179. data/guides/code/getting_started/config/application.rb +17 -0
  180. data/guides/code/getting_started/config/boot.rb +4 -0
  181. data/guides/code/getting_started/config/database.yml +25 -0
  182. data/guides/code/getting_started/config/environment.rb +5 -0
  183. data/guides/code/getting_started/config/environments/development.rb +30 -0
  184. data/guides/code/getting_started/config/environments/production.rb +80 -0
  185. data/guides/code/getting_started/config/environments/test.rb +36 -0
  186. data/guides/code/getting_started/config/initializers/backtrace_silencers.rb +7 -0
  187. data/guides/code/getting_started/config/initializers/filter_parameter_logging.rb +4 -0
  188. data/guides/code/getting_started/config/initializers/inflections.rb +16 -0
  189. data/guides/code/getting_started/config/initializers/locale.rb +9 -0
  190. data/guides/code/getting_started/config/initializers/mime_types.rb +5 -0
  191. data/guides/code/getting_started/config/initializers/secret_token.rb +12 -0
  192. data/guides/code/getting_started/config/initializers/session_store.rb +3 -0
  193. data/guides/code/getting_started/config/initializers/wrap_parameters.rb +14 -0
  194. data/guides/code/getting_started/config/locales/en.yml +23 -0
  195. data/guides/code/getting_started/config/routes.rb +7 -0
  196. data/guides/code/getting_started/db/migrate/20130122042648_create_posts.rb +10 -0
  197. data/guides/code/getting_started/db/migrate/20130122045842_create_comments.rb +11 -0
  198. data/guides/code/getting_started/db/schema.rb +33 -0
  199. data/guides/code/getting_started/db/seeds.rb +7 -0
  200. data/guides/code/getting_started/public/404.html +27 -0
  201. data/guides/code/getting_started/public/422.html +26 -0
  202. data/guides/code/getting_started/public/500.html +26 -0
  203. data/guides/code/getting_started/public/favicon.ico +0 -0
  204. data/guides/code/getting_started/public/robots.txt +5 -0
  205. data/guides/code/getting_started/test/controllers/comments_controller_test.rb +7 -0
  206. data/guides/code/getting_started/test/controllers/posts_controller_test.rb +7 -0
  207. data/guides/code/getting_started/test/controllers/welcome_controller_test.rb +9 -0
  208. data/guides/code/getting_started/test/fixtures/comments.yml +11 -0
  209. data/guides/code/getting_started/test/fixtures/posts.yml +9 -0
  210. data/guides/code/getting_started/test/helpers/comments_helper_test.rb +4 -0
  211. data/guides/code/getting_started/test/helpers/posts_helper_test.rb +4 -0
  212. data/guides/code/getting_started/test/helpers/welcome_helper_test.rb +4 -0
  213. data/guides/code/getting_started/test/models/comment_test.rb +7 -0
  214. data/guides/code/getting_started/test/models/post_test.rb +7 -0
  215. data/guides/code/getting_started/test/test_helper.rb +15 -0
  216. data/guides/rails_guides.rb +44 -0
  217. data/guides/rails_guides/generator.rb +248 -0
  218. data/guides/rails_guides/helpers.rb +51 -0
  219. data/guides/rails_guides/indexer.rb +68 -0
  220. data/guides/rails_guides/kindle.rb +119 -0
  221. data/guides/rails_guides/levenshtein.rb +31 -0
  222. data/guides/rails_guides/markdown.rb +163 -0
  223. data/guides/rails_guides/markdown/renderer.rb +82 -0
  224. data/guides/source/2_2_release_notes.md +435 -0
  225. data/guides/source/2_3_release_notes.md +621 -0
  226. data/guides/source/3_0_release_notes.md +614 -0
  227. data/guides/source/3_1_release_notes.md +556 -0
  228. data/guides/source/3_2_release_notes.md +565 -0
  229. data/guides/source/4_0_release_notes.md +228 -0
  230. data/guides/source/_license.html.erb +2 -0
  231. data/guides/source/_welcome.html.erb +19 -0
  232. data/guides/source/action_controller_overview.md +872 -0
  233. data/guides/source/action_mailer_basics.md +599 -0
  234. data/guides/source/action_view_overview.md +1565 -0
  235. data/guides/source/active_model_basics.md +200 -0
  236. data/guides/source/active_record_basics.md +370 -0
  237. data/guides/source/active_record_callbacks.md +358 -0
  238. data/guides/source/active_record_querying.md +1621 -0
  239. data/guides/source/active_record_validations.md +1128 -0
  240. data/guides/source/active_support_core_extensions.md +3791 -0
  241. data/guides/source/active_support_instrumentation.md +487 -0
  242. data/guides/source/api_documentation_guidelines.md +209 -0
  243. data/guides/source/asset_pipeline.md +832 -0
  244. data/guides/source/association_basics.md +2129 -0
  245. data/guides/source/caching_with_rails.md +350 -0
  246. data/guides/source/command_line.md +594 -0
  247. data/guides/source/configuring.md +736 -0
  248. data/guides/source/contributing_to_ruby_on_rails.md +455 -0
  249. data/guides/source/credits.html.erb +76 -0
  250. data/guides/source/debugging_rails_applications.md +675 -0
  251. data/guides/source/development_dependencies_install.md +195 -0
  252. data/guides/source/documents.yaml +179 -0
  253. data/guides/source/engines.md +961 -0
  254. data/guides/source/form_helpers.md +955 -0
  255. data/guides/source/generators.md +644 -0
  256. data/guides/source/getting_started.md +1775 -0
  257. data/guides/source/i18n.md +983 -0
  258. data/guides/source/index.html.erb +27 -0
  259. data/guides/source/initialization.md +562 -0
  260. data/guides/source/kindle/KINDLE.md +26 -0
  261. data/guides/source/kindle/copyright.html.erb +1 -0
  262. data/guides/source/kindle/layout.html.erb +27 -0
  263. data/guides/source/kindle/rails_guides.opf.erb +52 -0
  264. data/guides/source/kindle/toc.html.erb +24 -0
  265. data/guides/source/kindle/toc.ncx.erb +64 -0
  266. data/guides/source/kindle/welcome.html.erb +5 -0
  267. data/guides/source/layout.html.erb +148 -0
  268. data/guides/source/layouts_and_rendering.md +1132 -0
  269. data/guides/source/migrations.md +1059 -0
  270. data/guides/source/nested_model_forms.md +225 -0
  271. data/guides/source/plugins.md +435 -0
  272. data/guides/source/rails_application_templates.md +229 -0
  273. data/guides/source/rails_on_rack.md +342 -0
  274. data/guides/source/routing.md +1088 -0
  275. data/guides/source/ruby_on_rails_guides_guidelines.md +124 -0
  276. data/guides/source/security.md +973 -0
  277. data/guides/source/testing.md +981 -0
  278. data/guides/source/upgrading_ruby_on_rails.md +286 -0
  279. data/guides/source/working_with_javascript_in_rails.md +396 -0
  280. data/guides/w3c_validator.rb +95 -0
  281. metadata +315 -31
@@ -0,0 +1,209 @@
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 is generated with RDoc. Please consult the documentation for help with the [markup](http://rdoc.rubyforge.org/RDoc/Markup.html), and also take into account these [additional directives](http://rdoc.rubyforge.org/RDoc/Parser/Ruby.html).
17
+
18
+ Wording
19
+ -------
20
+
21
+ Write simple, declarative sentences. Brevity is a plus: get to the point.
22
+
23
+ Write in present tense: "Returns a hash that...", rather than "Returned a hash that..." or "Will return a hash that...".
24
+
25
+ Start comments in upper case. Follow regular punctuation rules:
26
+
27
+ ```ruby
28
+ # Declares an attribute reader backed by an internally-named
29
+ # instance variable.
30
+ def attr_internal_reader(*attrs)
31
+ ...
32
+ end
33
+ ```
34
+
35
+ 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.
36
+
37
+ 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?
38
+
39
+ 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.
40
+
41
+ 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.
42
+
43
+ Use the article "an" for "SQL", as in "an SQL statement". Also "an SQLite database".
44
+
45
+ English
46
+ -------
47
+
48
+ Please use American English (<em>color</em>, <em>center</em>, <em>modularize</em>, etc).. See [a list of American and British English spelling differences here](http://en.wikipedia.org/wiki/American_and_British_English_spelling_differences).
49
+
50
+ Example Code
51
+ ------------
52
+
53
+ Choose meaningful examples that depict and cover the basics as well as interesting points or gotchas.
54
+
55
+ 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).
56
+
57
+ Short docs do not need an explicit "Examples" label to introduce snippets; they just follow paragraphs:
58
+
59
+ ```ruby
60
+ # Converts a collection of elements into a formatted string by
61
+ # calling +to_s+ on all elements and joining them.
62
+ #
63
+ # Blog.all.to_formatted_s # => "First PostSecond PostThird Post"
64
+ ```
65
+
66
+ On the other hand, big chunks of structured documentation may have a separate "Examples" section:
67
+
68
+ ```ruby
69
+ # ==== Examples
70
+ #
71
+ # Person.exists?(5)
72
+ # Person.exists?('5')
73
+ # Person.exists?(name: "David")
74
+ # Person.exists?(['name LIKE ?', "%#{query}%"])
75
+ ```
76
+
77
+ The results of expressions follow them and are introduced by "# => ", vertically aligned:
78
+
79
+ ```ruby
80
+ # For checking if a fixnum is even or odd.
81
+ #
82
+ # 1.even? # => false
83
+ # 1.odd? # => true
84
+ # 2.even? # => true
85
+ # 2.odd? # => false
86
+ ```
87
+
88
+ If a line is too long, the comment may be placed on the next line:
89
+
90
+ ```ruby
91
+ # label(:post, :title)
92
+ # # => <label for="post_title">Title</label>
93
+ #
94
+ # label(:post, :title, "A short title")
95
+ # # => <label for="post_title">A short title</label>
96
+ #
97
+ # label(:post, :title, "A short title", class: "title_label")
98
+ # # => <label for="post_title" class="title_label">A short title</label>
99
+ ```
100
+
101
+ Avoid using any printing methods like `puts` or `p` for that purpose.
102
+
103
+ On the other hand, regular comments do not use an arrow:
104
+
105
+ ```ruby
106
+ # polymorphic_url(record) # same as comment_url(record)
107
+ ```
108
+
109
+ Filenames
110
+ ---------
111
+
112
+ As a rule of thumb, use filenames relative to the application root:
113
+
114
+ ```
115
+ config/routes.rb # YES
116
+ routes.rb # NO
117
+ RAILS_ROOT/config/routes.rb # NO
118
+ ```
119
+
120
+ Fonts
121
+ -----
122
+
123
+ ### Fixed-width Font
124
+
125
+ Use fixed-width fonts for:
126
+
127
+ * Constants, in particular class and module names.
128
+ * Method names.
129
+ * Literals like `nil`, `false`, `true`, `self`.
130
+ * Symbols.
131
+ * Method parameters.
132
+ * File names.
133
+
134
+ ```ruby
135
+ class Array
136
+ # Calls +to_param+ on all its elements and joins the result with
137
+ # slashes. This is used by +url_for+ in Action Pack.
138
+ def to_param
139
+ collect { |e| e.to_param }.join '/'
140
+ end
141
+ end
142
+ ```
143
+
144
+ WARNING: Using a pair of `+...+` for fixed-width font only works with **words**; that is: anything matching `\A\w+\z`. For anything else use `<tt>...</tt>`, notably symbols, setters, inline snippets, etc.
145
+
146
+ ### Regular Font
147
+
148
+ When "true" and "false" are English words rather than Ruby keywords use a regular font:
149
+
150
+ ```ruby
151
+ # Runs all the validations within the specified context.
152
+ # Returns true if no errors are found, false otherwise.
153
+ #
154
+ # If the argument is false (default is +nil+), the context is
155
+ # set to <tt>:create</tt> if <tt>new_record?</tt> is true,
156
+ # and to <tt>:update</tt> if it is not.
157
+ #
158
+ # Validations with no <tt>:on</tt> option will run no
159
+ # matter the context. Validations with # some <tt>:on</tt>
160
+ # option will only run in the specified context.
161
+ def valid?(context = nil)
162
+ ...
163
+ end
164
+ ```
165
+
166
+ Description Lists
167
+ -----------------
168
+
169
+ 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):
170
+
171
+ ```ruby
172
+ # * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
173
+ ```
174
+
175
+ The description starts in upper case and ends with a full stop—it's standard English.
176
+
177
+ Dynamically Generated Methods
178
+ -----------------------------
179
+
180
+ 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:
181
+
182
+ ```ruby
183
+ for severity in Severity.constants
184
+ class_eval <<-EOT, __FILE__, __LINE__
185
+ def #{severity.downcase}(message = nil, progname = nil, &block) # def debug(message = nil, progname = nil, &block)
186
+ add(#{severity}, message, progname, &block) # add(DEBUG, message, progname, &block)
187
+ end # end
188
+ #
189
+ def #{severity.downcase}? # def debug?
190
+ #{severity} >= @level # DEBUG >= @level
191
+ end # end
192
+ EOT
193
+ end
194
+ ```
195
+
196
+ If the resulting lines are too wide, say 200 columns or more, put the comment above the call:
197
+
198
+ ```ruby
199
+ # def self.find_by_login_and_activated(*args)
200
+ # options = args.extract_options!
201
+ # ...
202
+ # end
203
+ self.class_eval %{
204
+ def self.#{method_id}(*args)
205
+ options = args.extract_options!
206
+ ...
207
+ end
208
+ }
209
+ ```
@@ -0,0 +1,832 @@
1
+ The Asset Pipeline
2
+ ==================
3
+
4
+ This guide covers the asset pipeline.
5
+
6
+ After reading this guide, you will know:
7
+
8
+ * How to understand what the asset pipeline is and what it does.
9
+ * How to properly organize your application assets.
10
+ * How to understand 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 JavaScript and CSS assets. It also adds the ability to write these assets in other languages such as CoffeeScript, Sass and ERB.
20
+
21
+ Making the asset pipeline a core feature of Rails means that all developers can benefit from the power of having their assets pre-processed, compressed and minified by one central library, Sprockets. This is part of Rails' "fast by default" strategy as outlined by DHH in his keynote at RailsConf 2011.
22
+
23
+ The asset pipeline is enabled by default. It can be disabled in `config/application.rb` by putting this line inside the application class definition:
24
+
25
+ ```ruby
26
+ config.assets.enabled = false
27
+ ```
28
+
29
+ You can also disable the asset pipeline while creating a new application by passing the `--skip-sprockets` option.
30
+
31
+ ```bash
32
+ rails new appname --skip-sprockets
33
+ ```
34
+
35
+ You should use the defaults for all new applications unless you have a specific reason to avoid the asset pipeline.
36
+
37
+
38
+ ### Main Features
39
+
40
+ The first feature of the pipeline is to concatenate assets. This is important in a production environment, because it 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.
41
+
42
+ Rails 2.x introduced the ability to concatenate JavaScript and CSS assets by placing `cache: true` at the end of the `javascript_include_tag` and `stylesheet_link_tag` methods. But this technique has some limitations. For example, it cannot generate the caches in advance, and it is not able to transparently include assets provided by third-party libraries.
43
+
44
+ Starting with version 3.1, Rails defaults to concatenating all JavaScript files into one master `.js` file and all CSS files into one master `.css` 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.
45
+
46
+ 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.
47
+
48
+ The third feature of the asset pipeline is that 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.
49
+
50
+ ### What is Fingerprinting and Why Should I Care?
51
+
52
+ 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.
53
+
54
+ 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 _cache busting_.
55
+
56
+ The technique that Rails uses for fingerprinting is to insert a hash of the content into the name, usually at the end. For example a CSS file `global.css` could be renamed with an MD5 digest of its contents:
57
+
58
+ ```
59
+ global-908e25f4bf641868d8683022a5b62f54.css
60
+ ```
61
+
62
+ This is the strategy adopted by the Rails asset pipeline.
63
+
64
+ 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:
65
+
66
+ ```
67
+ /stylesheets/global.css?1309495796
68
+ ```
69
+
70
+ The query string strategy has several disadvantages:
71
+
72
+ 1. **Not all caches will reliably cache content where the filename only differs by query parameters**<br />
73
+ [Steve Souders recommends](http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/), "...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.
74
+
75
+ 2. **The file name can change between nodes in multi-server environments.**<br />
76
+ 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.
77
+ 3. **Too much cache invalidation**<br />
78
+ When static assets are deployed with each new release of code, the mtime of _all_ these files changes, forcing all remote clients to fetch them again, even when the content of those assets has not changed.
79
+
80
+ Fingerprinting fixes these problems by avoiding query strings, and by ensuring that filenames are consistent based on their content.
81
+
82
+ Fingerprinting is enabled by default for production and disabled for all other environments. You can enable or disable it in your configuration through the `config.assets.digest` option.
83
+
84
+ More reading:
85
+
86
+ * [Optimize caching](http://code.google.com/speed/page-speed/docs/caching.html)
87
+ * [Revving Filenames: don’t use querystring](http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/)
88
+
89
+
90
+ How to Use the Asset Pipeline
91
+ -----------------------------
92
+
93
+ In previous versions of Rails, all assets were located in subdirectories of `public` such as `images`, `javascripts` and `stylesheets`. With the asset pipeline, the preferred location for these assets is now the `app/assets` directory. Files in this directory are served by the Sprockets middleware included in the sprockets gem.
94
+
95
+ Assets can still be placed in the `public` hierarchy. Any assets under `public` will be served as static files by the application or web server. You should use `app/assets` for files that must undergo some pre-processing before they are served.
96
+
97
+ In production, Rails precompiles these files to `public/assets` by default. The precompiled copies are then served as static assets by the web server. The files in `app/assets` are never served directly in production.
98
+
99
+ ### Controller Specific Assets
100
+
101
+ When you generate a scaffold or a controller, Rails also generates a JavaScript file (or CoffeeScript file if the `coffee-rails` gem is in the `Gemfile`) and a Cascading Style Sheet file (or SCSS file if `sass-rails` is in the `Gemfile`) for that controller.
102
+
103
+ For example, if you generate a `ProjectsController`, Rails will also add a new file at `app/assets/javascripts/projects.js.coffee` and another at `app/assets/stylesheets/projects.css.scss`. By default these files will be ready to use by your application immediately using the `require_tree` directive. See [Manifest Files and Directives](#manifest-files-and-directives) for more details on require_tree.
104
+
105
+ You can also opt to include controller specific stylesheets and JavaScript files only in their respective controllers using the following: `<%= javascript_include_tag params[:controller] %>` or `<%= stylesheet_link_tag params[:controller] %>`. Ensure that you are not using the `require_tree` directive though, as this will result in your assets being included more than once.
106
+
107
+ WARNING: When using asset precompilation (the production default), 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. This will result in false positives during development as these files will work just fine since assets will be compiled on the fly. When running in production however, you will see 500 errors since live compilation is turned off by default. See [Precompiling Assets](#precompiling-assets) for more information on how precompiling works.
108
+
109
+ NOTE: 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 [ExecJS](https://github.com/sstephenson/execjs#readme) documentation to know all supported JavaScript runtimes.
110
+
111
+ You can also disable the generation of asset files when generating a controller by adding the following to your `config/application.rb` configuration:
112
+
113
+ ```ruby
114
+ config.generators do |g|
115
+ g.assets false
116
+ end
117
+ ```
118
+
119
+ ### Asset Organization
120
+
121
+ Pipeline assets can be placed inside an application in one of three locations: `app/assets`, `lib/assets` or `vendor/assets`.
122
+
123
+ * `app/assets` is for assets that are owned by the application, such as custom images, JavaScript files or stylesheets.
124
+
125
+ * `lib/assets` 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.
126
+
127
+ * `vendor/assets` is for assets that are owned by outside entities, such as code for JavaScript plugins and CSS frameworks.
128
+
129
+ #### Search Paths
130
+
131
+ When a file is referenced from a manifest or a helper, Sprockets searches the three default asset locations for it.
132
+
133
+ The default locations are: `app/assets/images` and the subdirectories `javascripts` and `stylesheets` in all three asset locations, but these subdirectories are not special. Any path under `assets/*` will be searched.
134
+
135
+ For example, these files:
136
+
137
+ ```
138
+ app/assets/javascripts/home.js
139
+ lib/assets/javascripts/moovinator.js
140
+ vendor/assets/javascripts/slider.js
141
+ vendor/assets/somepackage/phonebox.js
142
+ ```
143
+
144
+ would be referenced in a manifest like this:
145
+
146
+ ```js
147
+ //= require home
148
+ //= require moovinator
149
+ //= require slider
150
+ //= require phonebox
151
+ ```
152
+
153
+ Assets inside subdirectories can also be accessed.
154
+
155
+ ```
156
+ app/assets/javascripts/sub/something.js
157
+ ```
158
+
159
+ is referenced as:
160
+
161
+ ```js
162
+ //= require sub/something
163
+ ```
164
+
165
+ You can view the search path by inspecting `Rails.application.config.assets.paths` in the Rails console.
166
+
167
+ Besides the standard `assets/*` paths, additional (fully qualified) paths can be added to the pipeline in `config/application.rb`. For example:
168
+
169
+ ```ruby
170
+ config.assets.paths << Rails.root.join("lib", "videoplayer", "flash")
171
+ ```
172
+
173
+ Paths are traversed in the order that they occur in the search path. By default, this means the files in `app/assets` take precedence, and will mask corresponding paths in `lib` and `vendor`.
174
+
175
+ 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.
176
+
177
+ #### Using Index Files
178
+
179
+ Sprockets uses files named `index` (with the relevant extensions) for a special purpose.
180
+
181
+ For example, if you have a jQuery library with many modules, which is stored in `lib/assets/library_name`, the file `lib/assets/library_name/index.js` 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 `require_tree` directive.
182
+
183
+ The library as a whole can be accessed in the site's application manifest like so:
184
+
185
+ ```js
186
+ //= require library_name
187
+ ```
188
+
189
+ This simplifies maintenance and keeps things clean by allowing related code to be grouped before inclusion elsewhere.
190
+
191
+ ### Coding Links to Assets
192
+
193
+ Sprockets does not add any new methods to access your assets - you still use the familiar `javascript_include_tag` and `stylesheet_link_tag`.
194
+
195
+ ```erb
196
+ <%= stylesheet_link_tag "application" %>
197
+ <%= javascript_include_tag "application" %>
198
+ ```
199
+
200
+ In regular views you can access images in the `assets/images` directory like this:
201
+
202
+ ```erb
203
+ <%= image_tag "rails.png" %>
204
+ ```
205
+
206
+ 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 `public/assets/rails.png` it is served by the web server.
207
+
208
+ Alternatively, a request for a file with an MD5 hash such as `public/assets/rails-af27b6a414e6da00003503148be9b409.png` is treated the same way. How these hashes are generated is covered in the [In Production](#in-production) section later on in this guide.
209
+
210
+ Sprockets will also look through the paths specified in `config.assets.paths` which includes the standard application paths and any path added by Rails engines.
211
+
212
+ Images can also be organized into subdirectories if required, and they can be accessed by specifying the directory's name in the tag:
213
+
214
+ ```erb
215
+ <%= image_tag "icons/rails.png" %>
216
+ ```
217
+
218
+ WARNING: If you're precompiling your assets (see [In Production](#in-production) 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 `image_tag` and the other helpers with user-supplied data.
219
+
220
+ #### CSS and ERB
221
+
222
+ The asset pipeline automatically evaluates ERB. This means that if you add an `erb` extension to a CSS asset (for example, `application.css.erb`), then helpers like `asset_path` are available in your CSS rules:
223
+
224
+ ```css
225
+ .class { background-image: url(<%= asset_path 'image.png' %>) }
226
+ ```
227
+
228
+ 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 `app/assets/images/image.png`, which would be referenced here. If this image is already available in `public/assets` as a fingerprinted file, then that path is referenced.
229
+
230
+ If you want to use a [data URI](http://en.wikipedia.org/wiki/Data_URI_scheme) — a method of embedding the image data directly into the CSS file — you can use the `asset_data_uri` helper.
231
+
232
+ ```css
233
+ #logo { background: url(<%= asset_data_uri 'logo.png' %>) }
234
+ ```
235
+
236
+ This inserts a correctly-formatted data URI into the CSS source.
237
+
238
+ Note that the closing tag cannot be of the style `-%>`.
239
+
240
+ #### CSS and Sass
241
+
242
+ When using the asset pipeline, paths to assets must be re-written and `sass-rails` provides `-url` and `-path` helpers (hyphenated in Sass, underscored in Ruby) for the following asset classes: image, font, video, audio, JavaScript and stylesheet.
243
+
244
+ * `image-url("rails.png")` becomes `url(/assets/rails.png)`
245
+ * `image-path("rails.png")` becomes `"/assets/rails.png"`.
246
+
247
+ The more generic form can also be used but the asset path and class must both be specified:
248
+
249
+ * `asset-url("rails.png", image)` becomes `url(/assets/rails.png)`
250
+ * `asset-path("rails.png", image)` becomes `"/assets/rails.png"`
251
+
252
+ #### JavaScript/CoffeeScript and ERB
253
+
254
+ If you add an `erb` extension to a JavaScript asset, making it something such as `application.js.erb`, then you can use the `asset_path` helper in your JavaScript code:
255
+
256
+ ```js
257
+ $('#logo').attr({
258
+ src: "<%= asset_path('logo.png') %>"
259
+ });
260
+ ```
261
+
262
+ This writes the path to the particular asset being referenced.
263
+
264
+ Similarly, you can use the `asset_path` helper in CoffeeScript files with `erb` extension (e.g., `application.js.coffee.erb`):
265
+
266
+ ```js
267
+ $('#logo').attr src: "<%= asset_path('logo.png') %>"
268
+ ```
269
+
270
+ ### Manifest Files and Directives
271
+
272
+ Sprockets uses manifest files to determine which assets to include and serve. These manifest files contain _directives_ — 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 `Rails.application.config.assets.compress` 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 the file size enabling the browser to download it faster.
273
+
274
+
275
+ For example, a new Rails application includes a default `app/assets/javascripts/application.js` file which contains the following lines:
276
+
277
+ ```js
278
+ // ...
279
+ //= require jquery
280
+ //= require jquery_ujs
281
+ //= require_tree .
282
+ ```
283
+
284
+ In JavaScript files, the directives begin with `//=`. In this case, the file is using the `require` and the `require_tree` directives. The `require` directive is used to tell Sprockets the files that you wish to require. Here, you are requiring the files `jquery.js` and `jquery_ujs.js` that are available somewhere in the search path for Sprockets. You need not supply the extensions explicitly. Sprockets assumes you are requiring a `.js` file when done from within a `.js` file.
285
+
286
+ The `require_tree` directive tells Sprockets to recursively include _all_ JavaScript files in the specified directory into the output. These paths must be specified relative to the manifest file. You can also use the `require_directory` directive which includes all JavaScript files only in the directory specified, without recursion.
287
+
288
+ Directives are processed top to bottom, but the order in which files are included by `require_tree` 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 `require` directives prevents files from being included twice in the output.
289
+
290
+ Rails also creates a default `app/assets/stylesheets/application.css` file which contains these lines:
291
+
292
+ ```js
293
+ /* ...
294
+ *= require_self
295
+ *= require_tree .
296
+ */
297
+ ```
298
+
299
+ The directives that work in the JavaScript files also work in stylesheets (though obviously including stylesheets rather than JavaScript files). The `require_tree` directive in a CSS manifest works the same way as the JavaScript one, requiring all stylesheets from the current directory.
300
+
301
+ In this example `require_self` is used. This puts the CSS contained within the file (if any) at the precise location of the `require_self` call. If `require_self` is called more than once, only the last call is respected.
302
+
303
+ 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) instead of these Sprockets directives. Using Sprockets directives all Sass files exist within their own scope, making variables or mixins only available within the document they were defined in.
304
+
305
+ You can have as many manifest files as you need. For example the `admin.css` and `admin.js` manifest could contain the JS and CSS files that are used for the admin section of an application.
306
+
307
+ 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:
308
+
309
+ ```js
310
+ /* ...
311
+ *= require reset
312
+ *= require layout
313
+ *= require chrome
314
+ */
315
+ ```
316
+
317
+
318
+ ### Preprocessing
319
+
320
+ 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 `app/assets/javascripts/projects.js.coffee` and an `app/assets/stylesheets/projects.css.scss` file.
321
+
322
+ When these files are requested, they are processed by the processors provided by the `coffee-script` and `sass` gems and then sent back to the browser as JavaScript and CSS respectively.
323
+
324
+ 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 `app/assets/stylesheets/projects.css.scss.erb` is first processed as ERB, then SCSS, and finally served as CSS. The same applies to a JavaScript file — `app/assets/javascripts/projects.js.coffee.erb` is processed as ERB, then CoffeeScript, and served as JavaScript.
325
+
326
+ Keep in mind that the order of these preprocessors is important. For example, if you called your JavaScript file `app/assets/javascripts/projects.js.erb.coffee` then it would be processed with the CoffeeScript interpreter first, which wouldn't understand ERB and therefore you would run into problems.
327
+
328
+ In Development
329
+ --------------
330
+
331
+ In development mode, assets are served as separate files in the order they are specified in the manifest file.
332
+
333
+ This manifest `app/assets/javascripts/application.js`:
334
+
335
+ ```js
336
+ //= require core
337
+ //= require projects
338
+ //= require tickets
339
+ ```
340
+
341
+ would generate this HTML:
342
+
343
+ ```html
344
+ <script src="/assets/core.js?body=1"></script>
345
+ <script src="/assets/projects.js?body=1"></script>
346
+ <script src="/assets/tickets.js?body=1"></script>
347
+ ```
348
+
349
+ The `body` param is required by Sprockets.
350
+
351
+ ### Turning Debugging Off
352
+
353
+ You can turn off debug mode by updating `config/environments/development.rb` to include:
354
+
355
+ ```ruby
356
+ config.assets.debug = false
357
+ ```
358
+
359
+ 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:
360
+
361
+ ```html
362
+ <script src="/assets/application.js"></script>
363
+ ```
364
+
365
+ Assets are compiled and cached on the first request after the server is started. Sprockets sets a `must-revalidate` Cache-Control HTTP header to reduce request overhead on subsequent requests — on these the browser gets a 304 (Not Modified) response.
366
+
367
+ If any of the files in the manifest have changed between requests, the server responds with a new compiled file.
368
+
369
+ Debug mode can also be enabled in the Rails helper methods:
370
+
371
+ ```erb
372
+ <%= stylesheet_link_tag "application", debug: true %>
373
+ <%= javascript_include_tag "application", debug: true %>
374
+ ```
375
+
376
+ The `:debug` option is redundant if debug mode is on.
377
+
378
+ You could potentially also enable compression in development mode as a sanity check, and disable it on-demand as required for debugging.
379
+
380
+ In Production
381
+ -------------
382
+
383
+ In the production environment Rails uses the fingerprinting scheme outlined above. By default Rails assumes that assets have been precompiled and will be served as static assets by your web server.
384
+
385
+ 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.
386
+
387
+ For example this:
388
+
389
+ ```erb
390
+ <%= javascript_include_tag "application" %>
391
+ <%= stylesheet_link_tag "application" %>
392
+ ```
393
+
394
+ generates something like this:
395
+
396
+ ```html
397
+ <script src="/assets/application-908e25f4bf641868d8683022a5b62f54.js"></script>
398
+ <link href="/assets/application-4dd5b109ee3439da54f5bdfd78a80473.css" media="screen" rel="stylesheet" />
399
+ ```
400
+
401
+ Note: with the Asset Pipeline the :cache and :concat options aren't used anymore, delete these options from the `javascript_include_tag` and `stylesheet_link_tag`.
402
+
403
+
404
+ The fingerprinting behavior is controlled by the setting of `config.assets.digest` setting in Rails (which defaults to `true` for production and `false` for everything else).
405
+
406
+ NOTE: Under normal circumstances the default 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.
407
+
408
+ ### Precompiling Assets
409
+
410
+ Rails comes bundled with a rake task to compile the asset manifests and other files in the pipeline to the disk.
411
+
412
+ Compiled assets are written to the location specified in `config.assets.prefix`. By default, this is the `public/assets` directory.
413
+
414
+ 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.
415
+
416
+ The rake task is:
417
+
418
+ ```bash
419
+ $ bundle exec rake assets:precompile
420
+ ```
421
+
422
+ For faster asset precompiles, you can partially load your application by setting
423
+ `config.assets.initialize_on_precompile` to false in `config/application.rb`, though in that case templates
424
+ cannot see application objects or methods. **Heroku requires this to be false.**
425
+
426
+ WARNING: If you set `config.assets.initialize_on_precompile` to false, be sure to
427
+ test `rake assets:precompile` locally before deploying. It may expose bugs where
428
+ your assets reference application objects or methods, since those are still
429
+ in scope in development mode regardless of the value of this flag. Changing this flag also affects
430
+ engines. Engines can define assets for precompilation as well. Since the complete environment is not loaded,
431
+ engines (or other gems) will not be loaded, which can cause missing assets.
432
+
433
+ Capistrano (v2.8.0 and above) includes a recipe to handle this in deployment. Add the following line to `Capfile`:
434
+
435
+ ```ruby
436
+ load 'deploy/assets'
437
+ ```
438
+
439
+ This links the folder specified in `config.assets.prefix` to `shared/assets`. If you already use this shared folder you'll need to write your own deployment task.
440
+
441
+ It is important that this folder is shared between deployments so that remotely cached pages that reference the old compiled assets still work for the life of the cached page.
442
+
443
+ NOTE. If you are precompiling your assets locally, you can use `bundle install --without assets` on the server to avoid installing the assets gems (the gems in the assets group in the Gemfile).
444
+
445
+ The default matcher for compiling files includes `application.js`, `application.css` and all non-JS/CSS files (this will include all image assets automatically):
446
+
447
+ ```ruby
448
+ [ Proc.new { |path| !%w(.js .css).include?(File.extname(path)) }, /application.(css|js)$/ ]
449
+ ```
450
+
451
+ NOTE. The matcher (and other members of the precompile array; see below) is applied to final compiled file names. This means that anything that compiles to JS/CSS is excluded, as well as raw JS/CSS files; for example, `.coffee` and `.scss` files are **not** automatically included as they compile to JS/CSS.
452
+
453
+ If you have other manifests or individual stylesheets and JavaScript files to include, you can add them to the `precompile` array:
454
+
455
+ ```ruby
456
+ config.assets.precompile += ['admin.js', 'admin.css', 'swfObject.js']
457
+ ```
458
+
459
+ Or you can opt to precompile all assets with something like this:
460
+
461
+ ```ruby
462
+ # config/environments/production.rb
463
+ config.assets.precompile << Proc.new do |path|
464
+ if path =~ /\.(css|js)\z/
465
+ full_path = Rails.application.assets.resolve(path).to_path
466
+ app_assets_path = Rails.root.join('app', 'assets').to_path
467
+ if full_path.starts_with? app_assets_path
468
+ puts "including asset: " + full_path
469
+ true
470
+ else
471
+ puts "excluding asset: " + full_path
472
+ false
473
+ end
474
+ else
475
+ false
476
+ end
477
+ end
478
+ ```
479
+
480
+ NOTE. 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.
481
+
482
+ The rake task also generates a `manifest.yml` 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:
483
+
484
+ ```yaml
485
+ ---
486
+ rails.png: rails-bd9ad5a560b5a3a7be0808c5cd76a798.png
487
+ jquery-ui.min.js: jquery-ui-7e33882a28fc84ad0e0e47e46cbf901c.min.js
488
+ jquery.min.js: jquery-8a50feed8d29566738ad005e19fe1c2d.min.js
489
+ application.js: application-3fdab497b8fb70d20cfc5495239dfc29.js
490
+ application.css: application-8af74128f904600e41a6e39241464e03.css
491
+ ```
492
+
493
+ The default location for the manifest is the root of the location specified in `config.assets.prefix` ('/assets' by default).
494
+
495
+ NOTE: If there are missing precompiled files in production you will get an `Sprockets::Helpers::RailsHelper::AssetPaths::AssetNotPrecompiledError` exception indicating the name of the missing file(s).
496
+
497
+ #### Far-future Expires Header
498
+
499
+ Precompiled assets exist on the filesystem 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 them.
500
+
501
+ For Apache:
502
+
503
+ ```apache
504
+ # The Expires* directives requires the Apache module `mod_expires` to be enabled.
505
+ <Location /assets/>
506
+ # Use of ETag is discouraged when Last-Modified is present
507
+ Header unset ETag
508
+ FileETag None
509
+ # RFC says only cache for 1 year
510
+ ExpiresActive On
511
+ ExpiresDefault "access plus 1 year"
512
+ </Location>
513
+ ```
514
+
515
+ For nginx:
516
+
517
+ ```nginx
518
+ location ~ ^/assets/ {
519
+ expires 1y;
520
+ add_header Cache-Control public;
521
+
522
+ add_header ETag "";
523
+ break;
524
+ }
525
+ ```
526
+
527
+ #### GZip Compression
528
+
529
+ When files are precompiled, Sprockets also creates a [gzipped](http://en.wikipedia.org/wiki/Gzip) (.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.
530
+
531
+ Nginx is able to do this automatically enabling `gzip_static`:
532
+
533
+ ```nginx
534
+ location ~ ^/(assets)/ {
535
+ root /path/to/public;
536
+ gzip_static on; # to serve pre-gzipped version
537
+ expires max;
538
+ add_header Cache-Control public;
539
+ }
540
+ ```
541
+
542
+ This directive is available if the core module that provides this feature was compiled with the web server. Ubuntu packages, even `nginx-light` have the module compiled. Otherwise, you may need to perform a manual compilation:
543
+
544
+ ```bash
545
+ ./configure --with-http_gzip_static_module
546
+ ```
547
+
548
+ If you're compiling nginx with Phusion Passenger you'll need to pass that option when prompted.
549
+
550
+ A robust configuration for Apache is possible but tricky; please Google around. (Or help update this Guide if you have a good example configuration for Apache.)
551
+
552
+ ### Local Precompilation
553
+
554
+ There are several reasons why you might want to precompile your assets locally. Among them are:
555
+
556
+ * You may not have write access to your production file system.
557
+ * You may be deploying to more than one server, and want to avoid the duplication of work.
558
+ * You may be doing frequent deploys that do not include asset changes.
559
+
560
+ Local compilation allows you to commit the compiled files into source control, and deploy as normal.
561
+
562
+ There are two caveats:
563
+
564
+ * You must not run the Capistrano deployment task that precompiles assets.
565
+ * You must change the following two application configuration settings.
566
+
567
+ In `config/environments/development.rb`, place the following line:
568
+
569
+ ```ruby
570
+ config.assets.prefix = "/dev-assets"
571
+ ```
572
+
573
+ You will also need this in application.rb:
574
+
575
+ ```ruby
576
+ config.assets.initialize_on_precompile = false
577
+ ```
578
+
579
+ The `prefix` change makes Rails use a different URL for serving assets in development mode, and pass all requests to Sprockets. The prefix is still set to `/assets` in the production environment. Without this change, the application would serve the precompiled assets from `public/assets` in development, and you would not see any local changes until you compile assets again.
580
+
581
+ The `initialize_on_precompile` change tells the precompile task to run without invoking Rails. This is because the precompile task runs in production mode by default, and will attempt to connect to your specified production database. Please note that you cannot have code in pipeline files that relies on Rails resources (such as the database) when compiling locally with this option.
582
+
583
+ You will also need to ensure that any compressors or minifiers are available on your development system.
584
+
585
+ 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.
586
+
587
+ ### Live Compilation
588
+
589
+ 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.
590
+
591
+ To enable this option set:
592
+
593
+ ```ruby
594
+ config.assets.compile = true
595
+ ```
596
+
597
+ 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.
598
+
599
+ Sprockets also sets the `Cache-Control` HTTP header to `max-age=31536000`. 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.
600
+
601
+ This mode uses more memory, performs more poorly than the default and is not recommended.
602
+
603
+ 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:
604
+
605
+ ```ruby
606
+ group :production do
607
+ gem 'therubyracer'
608
+ end
609
+ ```
610
+
611
+ ### CDNs
612
+
613
+ If your assets are being served by a CDN, ensure they don't stick around in
614
+ your cache forever. This can cause problems. If you use
615
+ `config.action_controller.perform_caching = true`, Rack::Cache will use
616
+ `Rails.cache` to store assets. This can cause your cache to fill up quickly.
617
+
618
+ Every cache is different, so evaluate how your CDN handles caching and make
619
+ sure that it plays nicely with the pipeline. You may find quirks related to
620
+ your specific set up, you may not. The defaults nginx uses, for example,
621
+ should give you no problems when used as an HTTP cache.
622
+
623
+ Customizing the Pipeline
624
+ ------------------------
625
+
626
+ ### CSS Compression
627
+
628
+ There is currently one option for compressing CSS, YUI. The [YUI CSS compressor](http://developer.yahoo.com/yui/compressor/css.html) provides minification.
629
+
630
+ The following line enables YUI compression, and requires the `yui-compressor` gem.
631
+
632
+ ```ruby
633
+ config.assets.css_compressor = :yui
634
+ ```
635
+
636
+ The `config.assets.compress` must be set to `true` to enable CSS compression.
637
+
638
+ ### JavaScript Compression
639
+
640
+ Possible options for JavaScript compression are `:closure`, `:uglifier` and `:yui`. These require the use of the `closure-compiler`, `uglifier` or `yui-compressor` gems, respectively.
641
+
642
+ The default Gemfile includes [uglifier](https://github.com/lautis/uglifier). This gem wraps [UglifierJS](https://github.com/mishoo/UglifyJS) (written for NodeJS) in Ruby. It compresses your code by removing white space. It also includes other optimizations such as changing your `if` and `else` statements to ternary operators where possible.
643
+
644
+ The following line invokes `uglifier` for JavaScript compression.
645
+
646
+ ```ruby
647
+ config.assets.js_compressor = :uglifier
648
+ ```
649
+
650
+ Note that `config.assets.compress` must be set to `true` to enable JavaScript compression
651
+
652
+ NOTE: You will need an [ExecJS](https://github.com/sstephenson/execjs#readme) supported runtime in order to use `uglifier`. If you are using Mac OS X or Windows you have a JavaScript runtime installed in your operating system. Check the [ExecJS](https://github.com/sstephenson/execjs#readme) documentation for information on all of the supported JavaScript runtimes.
653
+
654
+ ### Using Your Own Compressor
655
+
656
+ The compressor config settings for CSS and JavaScript also take any object. This object must have a `compress` method that takes a string as the sole argument and it must return a string.
657
+
658
+ ```ruby
659
+ class Transformer
660
+ def compress(string)
661
+ do_something_returning_a_string(string)
662
+ end
663
+ end
664
+ ```
665
+
666
+ To enable this, pass a new object to the config option in `application.rb`:
667
+
668
+ ```ruby
669
+ config.assets.css_compressor = Transformer.new
670
+ ```
671
+
672
+
673
+ ### Changing the _assets_ Path
674
+
675
+ The public path that Sprockets uses by default is `/assets`.
676
+
677
+ This can be changed to something else:
678
+
679
+ ```ruby
680
+ config.assets.prefix = "/some_other_path"
681
+ ```
682
+
683
+ This is a handy option if you are updating an older project that didn't use the asset pipeline and that already uses this path or you wish to use this path for a new resource.
684
+
685
+ ### X-Sendfile Headers
686
+
687
+ The X-Sendfile header is a directive to the web server to ignore the response from the application, and instead serve a specified file from disk. This option is off by default, but can be enabled if your server supports it. When enabled, this passes responsibility for serving the file to the web server, which is faster.
688
+
689
+ Apache and nginx support this option, which can be enabled in `config/environments/production.rb`.
690
+
691
+ ```ruby
692
+ # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
693
+ # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
694
+ ```
695
+
696
+ WARNING: If you are upgrading an existing application and intend to use this option, take care to paste this configuration option only into `production.rb` and any other environments you define with production behavior (not `application.rb`).
697
+
698
+ Assets Cache Store
699
+ ------------------
700
+
701
+ The default Rails cache store will be used by Sprockets to cache assets in development and production. This can be changed by setting `config.assets.cache_store`.
702
+
703
+ ```ruby
704
+ config.assets.cache_store = :memory_store
705
+ ```
706
+
707
+ The options accepted by the assets cache store are the same as the application's cache store.
708
+
709
+ ```ruby
710
+ config.assets.cache_store = :memory_store, { :size => 32.megabytes }
711
+ ```
712
+
713
+ Adding Assets to Your Gems
714
+ --------------------------
715
+
716
+ Assets can also come from external sources in the form of gems.
717
+
718
+ A good example of this is the `jquery-rails` gem which comes with Rails as the standard JavaScript library gem. This gem contains an engine class which inherits from `Rails::Engine`. By doing this, Rails is informed that the directory for this gem may contain assets and the `app/assets`, `lib/assets` and `vendor/assets` directories of this engine are added to the search path of Sprockets.
719
+
720
+ Making Your Library or Gem a Pre-Processor
721
+ ------------------------------------------
722
+
723
+ As Sprockets uses [Tilt](https://github.com/rtomayko/tilt) as a generic
724
+ interface to different templating engines, your gem should just
725
+ implement the Tilt template protocol. Normally, you would subclass
726
+ `Tilt::Template` and reimplement `evaluate` method to return final
727
+ output. Template source is stored at `@code`. Have a look at
728
+ [`Tilt::Template`](https://github.com/rtomayko/tilt/blob/master/lib/tilt/template.rb)
729
+ sources to learn more.
730
+
731
+ ```ruby
732
+ module BangBang
733
+ class Template < ::Tilt::Template
734
+ # Adds a "!" to original template.
735
+ def evaluate(scope, locals, &block)
736
+ "#{@code}!"
737
+ end
738
+ end
739
+ end
740
+ ```
741
+
742
+ Now that you have a `Template` class, it's time to associate it with an
743
+ extenstion for template files:
744
+
745
+ ```ruby
746
+ Sprockets.register_engine '.bang', BangBang::Template
747
+ ```
748
+
749
+ Upgrading from Old Versions of Rails
750
+ ------------------------------------
751
+
752
+ There are a few issues when upgrading. The first is moving the files from `public/` to the new locations. See [Asset Organization](#asset-organization) above for guidance on the correct locations for different file types.
753
+
754
+ Next will be avoiding duplicate JavaScript files. Since jQuery is the default JavaScript library from Rails 3.1 onwards, you don't need to copy `jquery.js` into `app/assets` and it will be included automatically.
755
+
756
+ The third is updating the various environment files with the correct default options. The following changes reflect the defaults in version 3.1.0.
757
+
758
+ In `application.rb`:
759
+
760
+ ```ruby
761
+ # Enable the asset pipeline
762
+ config.assets.enabled = true
763
+
764
+ # Version of your assets, change this if you want to expire all your assets
765
+ config.assets.version = '1.0'
766
+
767
+ # Change the path that assets are served from
768
+ # config.assets.prefix = "/assets"
769
+ ```
770
+
771
+ In `development.rb`:
772
+
773
+ ```ruby
774
+ # Do not compress assets
775
+ config.assets.compress = false
776
+
777
+ # Expands the lines which load the assets
778
+ config.assets.debug = true
779
+ ```
780
+
781
+ And in `production.rb`:
782
+
783
+ ```ruby
784
+ # Compress JavaScripts and CSS
785
+ config.assets.compress = true
786
+
787
+ # Choose the compressors to use
788
+ # config.assets.js_compressor = :uglifier
789
+ # config.assets.css_compressor = :yui
790
+
791
+ # Don't fallback to assets pipeline if a precompiled asset is missed
792
+ config.assets.compile = false
793
+
794
+ # Generate digests for assets URLs.
795
+ config.assets.digest = true
796
+
797
+ # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
798
+ # config.assets.precompile += %w( search.js )
799
+ ```
800
+
801
+ You should not need to change `test.rb`. The defaults in the test environment are: `config.assets.compile` is true and `config.assets.compress`, `config.assets.debug` and `config.assets.digest` are false.
802
+
803
+ The following should also be added to `Gemfile`:
804
+
805
+ ```ruby
806
+ # Gems used only for assets and not required
807
+ # in production environments by default.
808
+ group :assets do
809
+ gem 'sass-rails', "~> 3.2.3"
810
+ gem 'coffee-rails', "~> 3.2.1"
811
+ gem 'uglifier'
812
+ end
813
+ ```
814
+
815
+ If you use the `assets` group with Bundler, please make sure that your `config/application.rb` has the following Bundler require statement:
816
+
817
+ ```ruby
818
+ if defined?(Bundler)
819
+ # If you precompile assets before deploying to production, use this line
820
+ Bundler.require *Rails.groups(:assets => %w(development test))
821
+ # If you want your assets lazily compiled in production, use this line
822
+ # Bundler.require(:default, :assets, Rails.env)
823
+ end
824
+ ```
825
+
826
+ Instead of the old Rails 3.0 version:
827
+
828
+ ```ruby
829
+ # If you have a Gemfile, require the gems listed there, including any gems
830
+ # you've limited to :test, :development, or :production.
831
+ Bundler.require(:default, Rails.env) if defined?(Bundler)
832
+ ```