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,350 @@
1
+ Caching with Rails: An overview
2
+ ===============================
3
+
4
+ This guide will teach you what you need to know about avoiding that expensive round-trip to your database and returning what you need to return to the web clients in the shortest time possible.
5
+
6
+ After reading this guide, you will know:
7
+
8
+ * Page, action, and fragment caching.
9
+ * Sweepers.
10
+ * Alternative cache stores.
11
+ * Conditional GET support.
12
+
13
+ --------------------------------------------------------------------------------
14
+
15
+ Basic Caching
16
+ -------------
17
+
18
+ This is an introduction to three types of caching techniques: page, action and
19
+ fragment caching. Rails provides by default fragment caching. In order to use
20
+ page and action caching, you will need to add `actionpack-page_caching` and
21
+ `actionpack-action_caching` to your Gemfile.
22
+
23
+ To start playing with caching you'll want to ensure that `config.action_controller.perform_caching` is set to `true`, if you're running in development mode. This flag is normally set in the corresponding `config/environments/*.rb` and caching is disabled by default for development and test, and enabled for production.
24
+
25
+ ```ruby
26
+ config.action_controller.perform_caching = true
27
+ ```
28
+
29
+ ### Page Caching
30
+
31
+ Page caching is a Rails mechanism which allows the request for a generated page to be fulfilled by the webserver (i.e. Apache or nginx), without ever having to go through the Rails stack at all. Obviously, this is super-fast. Unfortunately, it can't be applied to every situation (such as pages that need authentication) and since the webserver is literally just serving a file from the filesystem, cache expiration is an issue that needs to be dealt with.
32
+
33
+ INFO: Page Caching has been removed from Rails 4. See the [actionpack-page_caching gem](https://github.com/rails/actionpack-page_caching)
34
+
35
+ ### Action Caching
36
+
37
+ Page Caching cannot be used for actions that have before filters - for example, pages that require authentication. This is where Action Caching comes in. Action Caching works like Page Caching except the incoming web request hits the Rails stack so that before filters can be run on it before the cache is served. This allows authentication and other restrictions to be run while still serving the result of the output from a cached copy.
38
+
39
+ INFO: Action Caching has been removed from Rails 4. See the [actionpack-action_caching gem](https://github.com/rails/actionpack-action_caching)
40
+
41
+ ### Fragment Caching
42
+
43
+ Life would be perfect if we could get away with caching the entire contents of a page or action and serving it out to the world. Unfortunately, dynamic web applications usually build pages with a variety of components not all of which have the same caching characteristics. In order to address such a dynamically created page where different parts of the page need to be cached and expired differently, Rails provides a mechanism called Fragment Caching.
44
+
45
+ Fragment Caching allows a fragment of view logic to be wrapped in a cache block and served out of the cache store when the next request comes in.
46
+
47
+ As an example, if you wanted to show all the orders placed on your website in real time and didn't want to cache that part of the page, but did want to cache the part of the page which lists all products available, you could use this piece of code:
48
+
49
+ ```html+erb
50
+ <% Order.find_recent.each do |o| %>
51
+ <%= o.buyer.name %> bought <%= o.product.name %>
52
+ <% end %>
53
+
54
+ <% cache do %>
55
+ All available products:
56
+ <% Product.all.each do |p| %>
57
+ <%= link_to p.name, product_url(p) %>
58
+ <% end %>
59
+ <% end %>
60
+ ```
61
+
62
+ The cache block in our example will bind to the action that called it and is written out to the same place as the Action Cache, which means that if you want to cache multiple fragments per action, you should provide an `action_suffix` to the cache call:
63
+
64
+ ```html+erb
65
+ <% cache(action: 'recent', action_suffix: 'all_products') do %>
66
+ All available products:
67
+ ```
68
+
69
+ and you can expire it using the `expire_fragment` method, like so:
70
+
71
+ ```ruby
72
+ expire_fragment(controller: 'products', action: 'recent', action_suffix: 'all_products')
73
+ ```
74
+
75
+ If you don't want the cache block to bind to the action that called it, you can also use globally keyed fragments by calling the `cache` method with a key:
76
+
77
+ ```erb
78
+ <% cache('all_available_products') do %>
79
+ All available products:
80
+ <% end %>
81
+ ```
82
+
83
+ This fragment is then available to all actions in the `ProductsController` using the key and can be expired the same way:
84
+
85
+ ```ruby
86
+ expire_fragment('all_available_products')
87
+ ```
88
+ If you want to avoid expiring the fragment manually, whenever an action updates a product, you can define a helper method:
89
+
90
+ ```ruby
91
+ module ProductsHelper
92
+ def cache_key_for_products
93
+ count = Product.count
94
+ max_updated_at = Product.maximum(:updated_at).try(:utc).try(:to_s, :number)
95
+ "products/all-#{count}-#{max_updated_at}"
96
+ end
97
+ end
98
+ ```
99
+
100
+ This method generates a cache key that depends on all products and can be used in the view:
101
+
102
+ ```erb
103
+ <% cache(cache_key_for_products) do %>
104
+ All available products:
105
+ <% end %>
106
+ ```
107
+ You can also use an Active Record model as the cache key:
108
+
109
+ ```erb
110
+ <% Product.all.each do |p| %>
111
+ <% cache(p) do %>
112
+ <%= link_to p.name, product_url(p) %>
113
+ <% end %>
114
+ <% end %>
115
+ ```
116
+
117
+ Behind the scenes, a method called `cache_key` will be invoked on the model and it returns a string like `products/23-20130109142513`. The cache key includes the model name, the id and finally the updated_at timestamp. Thus it will automatically generate a new fragment when the product is updated because the key changes.
118
+
119
+ You can also combine the two schemes which is called "Russian Doll Caching":
120
+
121
+ ```erb
122
+ <% cache(cache_key_for_products) do %>
123
+ All available products:
124
+ <% Product.all.each do |p| %>
125
+ <% cache(p) do %>
126
+ <%= link_to p.name, product_url(p) %>
127
+ <% end %>
128
+ <% end %>
129
+ <% end %>
130
+ ```
131
+
132
+ It's called "Russian Doll Caching" because it nests multiple fragments. The advantage is that if a single product is updated, all the other inner fragments can be reused when regenerating the outer fragment.
133
+
134
+ ### SQL Caching
135
+
136
+ Query caching is a Rails feature that caches the result set returned by each query so that if Rails encounters the same query again for that request, it will use the cached result set as opposed to running the query against the database again.
137
+
138
+ For example:
139
+
140
+ ```ruby
141
+ class ProductsController < ApplicationController
142
+
143
+ def index
144
+ # Run a find query
145
+ @products = Product.all
146
+
147
+ ...
148
+
149
+ # Run the same query again
150
+ @products = Product.all
151
+ end
152
+
153
+ end
154
+ ```
155
+
156
+ Cache Stores
157
+ ------------
158
+
159
+ Rails provides different stores for the cached data created by <b>action</b> and <b>fragment</b> caches.
160
+
161
+ TIP: Page caches are always stored on disk.
162
+
163
+ ### Configuration
164
+
165
+ You can set up your application's default cache store by calling `config.cache_store=` in the Application definition inside your `config/application.rb` file or in an Application.configure block in an environment specific configuration file (i.e. `config/environments/*.rb`). The first argument will be the cache store to use and the rest of the argument will be passed as arguments to the cache store constructor.
166
+
167
+ ```ruby
168
+ config.cache_store = :memory_store
169
+ ```
170
+
171
+ NOTE: Alternatively, you can call `ActionController::Base.cache_store` outside of a configuration block.
172
+
173
+ You can access the cache by calling `Rails.cache`.
174
+
175
+ ### ActiveSupport::Cache::Store
176
+
177
+ This class provides the foundation for interacting with the cache in Rails. This is an abstract class and you cannot use it on its own. Rather you must use a concrete implementation of the class tied to a storage engine. Rails ships with several implementations documented below.
178
+
179
+ The main methods to call are `read`, `write`, `delete`, `exist?`, and `fetch`. The fetch method takes a block and will either return an existing value from the cache, or evaluate the block and write the result to the cache if no value exists.
180
+
181
+ There are some common options used by all cache implementations. These can be passed to the constructor or the various methods to interact with entries.
182
+
183
+ * `:namespace` - This option can be used to create a namespace within the cache store. It is especially useful if your application shares a cache with other applications. The default value will include the application name and Rails environment.
184
+
185
+ * `:compress` - This option can be used to indicate that compression should be used in the cache. This can be useful for transferring large cache entries over a slow network.
186
+
187
+ * `:compress_threshold` - This options is used in conjunction with the `:compress` option to indicate a threshold under which cache entries should not be compressed. This defaults to 16 kilobytes.
188
+
189
+ * `:expires_in` - This option sets an expiration time in seconds for the cache entry when it will be automatically removed from the cache.
190
+
191
+ * `:race_condition_ttl` - This option is used in conjunction with the `:expires_in` option. It will prevent race conditions when cache entries expire by preventing multiple processes from simultaneously regenerating the same entry (also known as the dog pile effect). This option sets the number of seconds that an expired entry can be reused while a new value is being regenerated. It's a good practice to set this value if you use the `:expires_in` option.
192
+
193
+ ### ActiveSupport::Cache::MemoryStore
194
+
195
+ This cache store keeps entries in memory in the same Ruby process. The cache store has a bounded size specified by the `:size` options to the initializer (default is 32Mb). When the cache exceeds the allotted size, a cleanup will occur and the least recently used entries will be removed.
196
+
197
+ ```ruby
198
+ config.cache_store = :memory_store, { size: 64.megabytes }
199
+ ```
200
+
201
+ If you're running multiple Ruby on Rails server processes (which is the case if you're using mongrel_cluster or Phusion Passenger), then your Rails server process instances won't be able to share cache data with each other. This cache store is not appropriate for large application deployments, but can work well for small, low traffic sites with only a couple of server processes or for development and test environments.
202
+
203
+ ### ActiveSupport::Cache::FileStore
204
+
205
+ This cache store uses the file system to store entries. The path to the directory where the store files will be stored must be specified when initializing the cache.
206
+
207
+ ```ruby
208
+ config.cache_store = :file_store, "/path/to/cache/directory"
209
+ ```
210
+
211
+ With this cache store, multiple server processes on the same host can share a cache. Servers processes running on different hosts could share a cache by using a shared file system, but that set up would not be ideal and is not recommended. The cache store is appropriate for low to medium traffic sites that are served off one or two hosts.
212
+
213
+ Note that the cache will grow until the disk is full unless you periodically clear out old entries.
214
+
215
+ This is the default cache store implementation.
216
+
217
+ ### ActiveSupport::Cache::MemCacheStore
218
+
219
+ This cache store uses Danga's `memcached` server to provide a centralized cache for your application. Rails uses the bundled `dalli` gem by default. This is currently the most popular cache store for production websites. It can be used to provide a single, shared cache cluster with very a high performance and redundancy.
220
+
221
+ When initializing the cache, you need to specify the addresses for all memcached servers in your cluster. If none is specified, it will assume memcached is running on the local host on the default port, but this is not an ideal set up for larger sites.
222
+
223
+ The `write` and `fetch` methods on this cache accept two additional options that take advantage of features specific to memcached. You can specify `:raw` to send a value directly to the server with no serialization. The value must be a string or number. You can use memcached direct operation like `increment` and `decrement` only on raw values. You can also specify `:unless_exist` if you don't want memcached to overwrite an existing entry.
224
+
225
+ ```ruby
226
+ config.cache_store = :mem_cache_store, "cache-1.example.com", "cache-2.example.com"
227
+ ```
228
+
229
+ ### ActiveSupport::Cache::EhcacheStore
230
+
231
+ If you are using JRuby you can use Terracotta's Ehcache as the cache store for your application. Ehcache is an open source Java cache that also offers an enterprise version with increased scalability, management, and commercial support. You must first install the jruby-ehcache-rails3 gem (version 1.1.0 or later) to use this cache store.
232
+
233
+ ```ruby
234
+ config.cache_store = :ehcache_store
235
+ ```
236
+
237
+ When initializing the cache, you may use the `:ehcache_config` option to specify the Ehcache config file to use (where the default is "ehcache.xml" in your Rails config directory), and the :cache_name option to provide a custom name for your cache (the default is rails_cache).
238
+
239
+ In addition to the standard `:expires_in` option, the `write` method on this cache can also accept the additional `:unless_exist` option, which will cause the cache store to use Ehcache's `putIfAbsent` method instead of `put`, and therefore will not overwrite an existing entry. Additionally, the `write` method supports all of the properties exposed by the [Ehcache Element class](http://ehcache.org/apidocs/net/sf/ehcache/Element.html) , including:
240
+
241
+ | Property | Argument Type | Description |
242
+ | --------------------------- | ------------------- | ----------------------------------------------------------- |
243
+ | elementEvictionData | ElementEvictionData | Sets this element's eviction data instance. |
244
+ | eternal | boolean | Sets whether the element is eternal. |
245
+ | timeToIdle, tti | int | Sets time to idle |
246
+ | timeToLive, ttl, expires_in | int | Sets time to Live |
247
+ | version | long | Sets the version attribute of the ElementAttributes object. |
248
+
249
+ These options are passed to the `write` method as Hash options using either camelCase or underscore notation, as in the following examples:
250
+
251
+ ```ruby
252
+ Rails.cache.write('key', 'value', time_to_idle: 60.seconds, timeToLive: 600.seconds)
253
+ caches_action :index, expires_in: 60.seconds, unless_exist: true
254
+ ```
255
+
256
+ For more information about Ehcache, see [http://ehcache.org/](http://ehcache.org/) .
257
+ For more information about Ehcache for JRuby and Rails, see [http://ehcache.org/documentation/jruby.html](http://ehcache.org/documentation/jruby.html)
258
+
259
+ ### ActiveSupport::Cache::NullStore
260
+
261
+ This cache store implementation is meant to be used only in development or test environments and it never stores anything. This can be very useful in development when you have code that interacts directly with `Rails.cache`, but caching may interfere with being able to see the results of code changes. With this cache store, all `fetch` and `read` operations will result in a miss.
262
+
263
+ ```ruby
264
+ config.cache_store = :null_store
265
+ ```
266
+
267
+ ### Custom Cache Stores
268
+
269
+ You can create your own custom cache store by simply extending `ActiveSupport::Cache::Store` and implementing the appropriate methods. In this way, you can swap in any number of caching technologies into your Rails application.
270
+
271
+ To use a custom cache store, simple set the cache store to a new instance of the class.
272
+
273
+ ```ruby
274
+ config.cache_store = MyCacheStore.new
275
+ ```
276
+
277
+ ### Cache Keys
278
+
279
+ The keys used in a cache can be any object that responds to either `:cache_key` or to `:to_param`. You can implement the `:cache_key` method on your classes if you need to generate custom keys. Active Record will generate keys based on the class name and record id.
280
+
281
+ You can use Hashes and Arrays of values as cache keys.
282
+
283
+ ```ruby
284
+ # This is a legal cache key
285
+ Rails.cache.read(site: "mysite", owners: [owner_1, owner_2])
286
+ ```
287
+
288
+ The keys you use on `Rails.cache` will not be the same as those actually used with the storage engine. They may be modified with a namespace or altered to fit technology backend constraints. This means, for instance, that you can't save values with `Rails.cache` and then try to pull them out with the `memcache-client` gem. However, you also don't need to worry about exceeding the memcached size limit or violating syntax rules.
289
+
290
+ Conditional GET support
291
+ -----------------------
292
+
293
+ Conditional GETs are a feature of the HTTP specification that provide a way for web servers to tell browsers that the response to a GET request hasn't changed since the last request and can be safely pulled from the browser cache.
294
+
295
+ They work by using the `HTTP_IF_NONE_MATCH` and `HTTP_IF_MODIFIED_SINCE` headers to pass back and forth both a unique content identifier and the timestamp of when the content was last changed. If the browser makes a request where the content identifier (etag) or last modified since timestamp matches the server’s version then the server only needs to send back an empty response with a not modified status.
296
+
297
+ It is the server's (i.e. our) responsibility to look for a last modified timestamp and the if-none-match header and determine whether or not to send back the full response. With conditional-get support in Rails this is a pretty easy task:
298
+
299
+ ```ruby
300
+ class ProductsController < ApplicationController
301
+
302
+ def show
303
+ @product = Product.find(params[:id])
304
+
305
+ # If the request is stale according to the given timestamp and etag value
306
+ # (i.e. it needs to be processed again) then execute this block
307
+ if stale?(last_modified: @product.updated_at.utc, etag: @product.cache_key)
308
+ respond_to do |wants|
309
+ # ... normal response processing
310
+ end
311
+ end
312
+
313
+ # If the request is fresh (i.e. it's not modified) then you don't need to do
314
+ # anything. The default render checks for this using the parameters
315
+ # used in the previous call to stale? and will automatically send a
316
+ # :not_modified. So that's it, you're done.
317
+ end
318
+ end
319
+ ```
320
+
321
+ Instead of a options hash, you can also simply pass in a model, Rails will use the `updated_at` and `cache_key` methods for setting `last_modified` and `etag`:
322
+
323
+ ```ruby
324
+ class ProductsController < ApplicationController
325
+ def show
326
+ @product = Product.find(params[:id])
327
+ respond_with(@product) if stale?(@product)
328
+ end
329
+ end
330
+ ```
331
+
332
+ If you don't have any special response processing and are using the default rendering mechanism (i.e. you're not using respond_to or calling render yourself) then you’ve got an easy helper in fresh_when:
333
+
334
+ ```ruby
335
+ class ProductsController < ApplicationController
336
+
337
+ # This will automatically send back a :not_modified if the request is fresh,
338
+ # and will render the default template (product.*) if it's stale.
339
+
340
+ def show
341
+ @product = Product.find(params[:id])
342
+ fresh_when last_modified: @product.published_at.utc, etag: @product
343
+ end
344
+ end
345
+ ```
346
+
347
+ Further reading
348
+ ---------------
349
+
350
+ * [Scaling Rails Screencasts](http://railslab.newrelic.com/scaling-rails)
@@ -0,0 +1,594 @@
1
+ The Rails Command Line
2
+ ======================
3
+
4
+ Rails comes with every command line tool you'll need to
5
+
6
+ After reading this guide, you will know:
7
+
8
+ * How to create a Rails application.
9
+ * How to generate models, controllers, database migrations, and unit tests.
10
+ * How to start a development server.
11
+ * How to experiment with objects through an interactive shell.
12
+ * How to profile and benchmark your new creation.
13
+
14
+ --------------------------------------------------------------------------------
15
+
16
+ NOTE: This tutorial assumes you have basic Rails knowledge from reading the [Getting Started with Rails Guide](getting_started.html).
17
+
18
+ Command Line Basics
19
+ -------------------
20
+
21
+ There are a few commands that are absolutely critical to your everyday usage of Rails. In the order of how much you'll probably use them are:
22
+
23
+ * `rails console`
24
+ * `rails server`
25
+ * `rake`
26
+ * `rails generate`
27
+ * `rails dbconsole`
28
+ * `rails new app_name`
29
+
30
+ Let's create a simple Rails application to step through each of these commands in context.
31
+
32
+ ### `rails new`
33
+
34
+ The first thing we'll want to do is create a new Rails application by running the `rails new` command after installing Rails.
35
+
36
+ INFO: You can install the rails gem by typing `gem install rails`, if you don't have it already.
37
+
38
+ ```bash
39
+ $ rails new commandsapp
40
+ create
41
+ create README.rdoc
42
+ create Rakefile
43
+ create config.ru
44
+ create .gitignore
45
+ create Gemfile
46
+ create app
47
+ ...
48
+ create tmp/cache
49
+ ...
50
+ run bundle install
51
+ ```
52
+
53
+ Rails will set you up with what seems like a huge amount of stuff for such a tiny command! You've got the entire Rails directory structure now with all the code you need to run our simple application right out of the box.
54
+
55
+ ### `rails server`
56
+
57
+ The `rails server` command launches a small web server named WEBrick which comes bundled with Ruby. You'll use this any time you want to access your application through a web browser.
58
+
59
+ INFO: WEBrick isn't your only option for serving Rails. We'll get to that [later](#server-with-different-backends).
60
+
61
+ With no further work, `rails server` will run our new shiny Rails app:
62
+
63
+ ```bash
64
+ $ cd commandsapp
65
+ $ rails server
66
+ => Booting WEBrick
67
+ => Rails 3.2.3 application starting in development on http://0.0.0.0:3000
68
+ => Call with -d to detach
69
+ => Ctrl-C to shutdown server
70
+ [2012-05-28 00:39:41] INFO WEBrick 1.3.1
71
+ [2012-05-28 00:39:41] INFO ruby 1.9.2 (2011-02-18) [x86_64-darwin11.2.0]
72
+ [2012-05-28 00:39:41] INFO WEBrick::HTTPServer#start: pid=69680 port=3000
73
+ ```
74
+
75
+ With just three commands we whipped up a Rails server listening on port 3000. Go to your browser and open [http://localhost:3000](http://localhost:3000), you will see a basic Rails app running.
76
+
77
+ INFO: You can also use the alias "s" to start the server: `rails s`.
78
+
79
+ The server can be run on a different port using the `-p` option. The default development environment can be changed using `-e`.
80
+
81
+ ```bash
82
+ $ rails server -e production -p 4000
83
+ ```
84
+
85
+ The `-b` option binds Rails to the specified ip, by default it is 0.0.0.0. You can run a server as a daemon by passing a `-d` option.
86
+
87
+ ### `rails generate`
88
+
89
+ The `rails generate` command uses templates to create a whole lot of things. Running `rails generate` by itself gives a list of available generators:
90
+
91
+ INFO: You can also use the alias "g" to invoke the generator command: `rails g`.
92
+
93
+ ```bash
94
+ $ rails generate
95
+ Usage: rails generate GENERATOR [args] [options]
96
+
97
+ ...
98
+ ...
99
+
100
+ Please choose a generator below.
101
+
102
+ Rails:
103
+ assets
104
+ controller
105
+ generator
106
+ ...
107
+ ...
108
+ ```
109
+
110
+ NOTE: You can install more generators through generator gems, portions of plugins you'll undoubtedly install, and you can even create your own!
111
+
112
+ Using generators will save you a large amount of time by writing **boilerplate code**, code that is necessary for the app to work.
113
+
114
+ Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator:
115
+
116
+ INFO: All Rails console utilities have help text. As with most *nix utilities, you can try adding `--help` or `-h` to the end, for example `rails server --help`.
117
+
118
+ ```bash
119
+ $ rails generate controller
120
+ Usage: rails generate controller NAME [action action] [options]
121
+
122
+ ...
123
+ ...
124
+
125
+ Description:
126
+ ...
127
+
128
+ To create a controller within a module, specify the controller name as a
129
+ path like 'parent_module/controller_name'.
130
+
131
+ ...
132
+
133
+ Example:
134
+ `rails generate controller CreditCard open debit credit close`
135
+
136
+ Credit card controller with URLs like /credit_card/debit.
137
+ Controller: app/controllers/credit_card_controller.rb
138
+ Test: test/controllers/credit_card_controller_test.rb
139
+ Views: app/views/credit_card/debit.html.erb [...]
140
+ Helper: app/helpers/credit_card_helper.rb
141
+ ```
142
+
143
+ The controller generator is expecting parameters in the form of `generate controller ControllerName action1 action2`. Let's make a `Greetings` controller with an action of **hello**, which will say something nice to us.
144
+
145
+ ```bash
146
+ $ rails generate controller Greetings hello
147
+ create app/controllers/greetings_controller.rb
148
+ route get "greetings/hello"
149
+ invoke erb
150
+ create app/views/greetings
151
+ create app/views/greetings/hello.html.erb
152
+ invoke test_unit
153
+ create test/controllers/greetings_controller_test.rb
154
+ invoke helper
155
+ create app/helpers/greetings_helper.rb
156
+ invoke test_unit
157
+ create test/helpers/greetings_helper_test.rb
158
+ invoke assets
159
+ invoke coffee
160
+ create app/assets/javascripts/greetings.js.coffee
161
+ invoke scss
162
+ create app/assets/stylesheets/greetings.css.scss
163
+ ```
164
+
165
+ What all did this generate? It made sure a bunch of directories were in our application, and created a controller file, a view file, a functional test file, a helper for the view, a JavaScript file and a stylesheet file.
166
+
167
+ Check out the controller and modify it a little (in `app/controllers/greetings_controller.rb`):
168
+
169
+ ```ruby
170
+ class GreetingsController < ApplicationController
171
+ def hello
172
+ @message = "Hello, how are you today?"
173
+ end
174
+ end
175
+ ```
176
+
177
+ Then the view, to display our message (in `app/views/greetings/hello.html.erb`):
178
+
179
+ ```erb
180
+ <h1>A Greeting for You!</h1>
181
+ <p><%= @message %></p>
182
+ ```
183
+
184
+ Fire up your server using `rails server`.
185
+
186
+ ```bash
187
+ $ rails server
188
+ => Booting WEBrick...
189
+ ```
190
+
191
+ The URL will be [http://localhost:3000/greetings/hello](http://localhost:3000/greetings/hello).
192
+
193
+ INFO: With a normal, plain-old Rails application, your URLs will generally follow the pattern of http://(host)/(controller)/(action), and a URL like http://(host)/(controller) will hit the **index** action of that controller.
194
+
195
+ Rails comes with a generator for data models too.
196
+
197
+ ```bash
198
+ $ rails generate model
199
+ Usage:
200
+ rails generate model NAME [field[:type][:index] field[:type][:index]] [options]
201
+
202
+ ...
203
+
204
+ ActiveRecord options:
205
+ [--migration] # Indicates when to generate migration
206
+ # Default: true
207
+
208
+ ...
209
+
210
+ Description:
211
+ Create rails files for model generator.
212
+ ```
213
+
214
+ NOTE: For a list of available field types, refer to the [API documentation](http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html#method-i-column) for the column method for the `TableDefinition` class.
215
+
216
+ But instead of generating a model directly (which we'll be doing later), let's set up a scaffold. A **scaffold** in Rails is a full set of model, database migration for that model, controller to manipulate it, views to view and manipulate the data, and a test suite for each of the above.
217
+
218
+ We will set up a simple resource called "HighScore" that will keep track of our highest score on video games we play.
219
+
220
+ ```bash
221
+ $ rails generate scaffold HighScore game:string score:integer
222
+ invoke active_record
223
+ create db/migrate/20120528060026_create_high_scores.rb
224
+ create app/models/high_score.rb
225
+ invoke test_unit
226
+ create test/models/high_score_test.rb
227
+ create test/fixtures/high_scores.yml
228
+ invoke resource_route
229
+ route resources :high_scores
230
+ invoke scaffold_controller
231
+ create app/controllers/high_scores_controller.rb
232
+ invoke erb
233
+ create app/views/high_scores
234
+ create app/views/high_scores/index.html.erb
235
+ create app/views/high_scores/edit.html.erb
236
+ create app/views/high_scores/show.html.erb
237
+ create app/views/high_scores/new.html.erb
238
+ create app/views/high_scores/_form.html.erb
239
+ invoke test_unit
240
+ create test/controllers/high_scores_controller_test.rb
241
+ invoke helper
242
+ create app/helpers/high_scores_helper.rb
243
+ invoke test_unit
244
+ create test/helpers/high_scores_helper_test.rb
245
+ invoke assets
246
+ invoke coffee
247
+ create app/assets/javascripts/high_scores.js.coffee
248
+ invoke scss
249
+ create app/assets/stylesheets/high_scores.css.scss
250
+ invoke scss
251
+ create app/assets/stylesheets/scaffolds.css.scss
252
+ ```
253
+
254
+ The generator checks that there exist the directories for models, controllers, helpers, layouts, functional and unit tests, stylesheets, creates the views, controller, model and database migration for HighScore (creating the `high_scores` table and fields), takes care of the route for the **resource**, and new tests for everything.
255
+
256
+ The migration requires that we **migrate**, that is, run some Ruby code (living in that `20120528060026_create_high_scores.rb`) to modify the schema of our database. Which database? The sqlite3 database that Rails will create for you when we run the `rake db:migrate` command. We'll talk more about Rake in-depth in a little while.
257
+
258
+ ```bash
259
+ $ rake db:migrate
260
+ == CreateHighScores: migrating ===============================================
261
+ -- create_table(:high_scores)
262
+ -> 0.0017s
263
+ == CreateHighScores: migrated (0.0019s) ======================================
264
+ ```
265
+
266
+ INFO: Let's talk about unit tests. Unit tests are code that tests and makes assertions about code. In unit testing, we take a little part of code, say a method of a model, and test its inputs and outputs. Unit tests are your friend. The sooner you make peace with the fact that your quality of life will drastically increase when you unit test your code, the better. Seriously. We'll make one in a moment.
267
+
268
+ Let's see the interface Rails created for us.
269
+
270
+ ```bash
271
+ $ rails server
272
+ ```
273
+
274
+ Go to your browser and open [http://localhost:3000/high_scores](http://localhost:3000/high_scores), now we can create new high scores (55,160 on Space Invaders!)
275
+
276
+ ### `rails console`
277
+
278
+ The `console` command lets you interact with your Rails application from the command line. On the underside, `rails console` uses IRB, so if you've ever used it, you'll be right at home. This is useful for testing out quick ideas with code and changing data server-side without touching the website.
279
+
280
+ INFO: You can also use the alias "c" to invoke the console: `rails c`.
281
+
282
+ You can specify the environment in which the `console` command should operate.
283
+
284
+ ```bash
285
+ $ rails console staging
286
+ ```
287
+
288
+ If you wish to test out some code without changing any data, you can do that by invoking `rails console --sandbox`.
289
+
290
+ ```bash
291
+ $ rails console --sandbox
292
+ Loading development environment in sandbox (Rails 3.2.3)
293
+ Any modifications you make will be rolled back on exit
294
+ irb(main):001:0>
295
+ ```
296
+
297
+ ### `rails dbconsole`
298
+
299
+ `rails dbconsole` figures out which database you're using and drops you into whichever command line interface you would use with it (and figures out the command line parameters to give to it, too!). It supports MySQL, PostgreSQL, SQLite and SQLite3.
300
+
301
+ INFO: You can also use the alias "db" to invoke the dbconsole: `rails db`.
302
+
303
+ ### `rails runner`
304
+
305
+ `runner` runs Ruby code in the context of Rails non-interactively. For instance:
306
+
307
+ ```bash
308
+ $ rails runner "Model.long_running_method"
309
+ ```
310
+
311
+ INFO: You can also use the alias "r" to invoke the runner: `rails r`.
312
+
313
+ You can specify the environment in which the `runner` command should operate using the `-e` switch.
314
+
315
+ ```bash
316
+ $ rails runner -e staging "Model.long_running_method"
317
+ ```
318
+
319
+ ### `rails destroy`
320
+
321
+ Think of `destroy` as the opposite of `generate`. It'll figure out what generate did, and undo it.
322
+
323
+ INFO: You can also use the alias "d" to invoke the destroy command: `rails d`.
324
+
325
+ ```bash
326
+ $ rails generate model Oops
327
+ invoke active_record
328
+ create db/migrate/20120528062523_create_oops.rb
329
+ create app/models/oops.rb
330
+ invoke test_unit
331
+ create test/models/oops_test.rb
332
+ create test/fixtures/oops.yml
333
+ ```
334
+ ```bash
335
+ $ rails destroy model Oops
336
+ invoke active_record
337
+ remove db/migrate/20120528062523_create_oops.rb
338
+ remove app/models/oops.rb
339
+ invoke test_unit
340
+ remove test/models/oops_test.rb
341
+ remove test/fixtures/oops.yml
342
+ ```
343
+
344
+ Rake
345
+ ----
346
+
347
+ Rake is Ruby Make, a standalone Ruby utility that replaces the Unix utility 'make', and uses a 'Rakefile' and `.rake` files to build up a list of tasks. In Rails, Rake is used for common administration tasks, especially sophisticated ones that build off of each other.
348
+
349
+ You can get a list of Rake tasks available to you, which will often depend on your current directory, by typing `rake --tasks`. Each task has a description, and should help you find the thing you need.
350
+
351
+ ```bash
352
+ $ rake --tasks
353
+ rake about # List versions of all Rails frameworks and the environment
354
+ rake assets:clean # Remove compiled assets
355
+ rake assets:precompile # Compile all the assets named in config.assets.precompile
356
+ rake db:create # Create the database from config/database.yml for the current Rails.env
357
+ ...
358
+ rake log:clear # Truncates all *.log files in log/ to zero bytes (specify which logs with LOGS=test,development)
359
+ rake middleware # Prints out your Rack middleware stack
360
+ ...
361
+ rake tmp:clear # Clear session, cache, and socket files from tmp/ (narrow w/ tmp:sessions:clear, tmp:cache:clear, tmp:sockets:clear)
362
+ rake tmp:create # Creates tmp directories for sessions, cache, sockets, and pids
363
+ ```
364
+
365
+ ### `about`
366
+
367
+ `rake about` gives information about version numbers for Ruby, RubyGems, Rails, the Rails subcomponents, your application's folder, the current Rails environment name, your app's database adapter, and schema version. It is useful when you need to ask for help, check if a security patch might affect you, or when you need some stats for an existing Rails installation.
368
+
369
+ ```bash
370
+ $ rake about
371
+ About your application's environment
372
+ Ruby version 1.9.3 (x86_64-linux)
373
+ RubyGems version 1.3.6
374
+ Rack version 1.3
375
+ Rails version 4.0.0.beta
376
+ JavaScript Runtime Node.js (V8)
377
+ Active Record version 4.0.0.beta
378
+ Action Pack version 4.0.0.beta
379
+ Action Mailer version 4.0.0.beta
380
+ Active Support version 4.0.0.beta
381
+ Middleware ActionDispatch::Static, Rack::Lock, Rack::Runtime, Rack::MethodOverride, ActionDispatch::RequestId, Rails::Rack::Logger, ActionDispatch::ShowExceptions, ActionDispatch::DebugExceptions, ActionDispatch::RemoteIp, ActionDispatch::Reloader, ActionDispatch::Callbacks, ActiveRecord::Migration::CheckPending, ActiveRecord::ConnectionAdapters::ConnectionManagement, ActiveRecord::QueryCache, ActionDispatch::Cookies, ActionDispatch::Session::EncryptedCookieStore, ActionDispatch::Flash, ActionDispatch::ParamsParser, Rack::Head, Rack::ConditionalGet, Rack::ETag
382
+ Application root /home/foobar/commandsapp
383
+ Environment development
384
+ Database adapter sqlite3
385
+ Database schema version 20110805173523
386
+ ```
387
+
388
+ ### `assets`
389
+
390
+ You can precompile the assets in `app/assets` using `rake assets:precompile` and remove those compiled assets using `rake assets:clean`.
391
+
392
+ ### `db`
393
+
394
+ The most common tasks of the `db:` Rake namespace are `migrate` and `create`, and it will pay off to try out all of the migration rake tasks (`up`, `down`, `redo`, `reset`). `rake db:version` is useful when troubleshooting, telling you the current version of the database.
395
+
396
+ More information about migrations can be found in the [Migrations](migrations.html) guide.
397
+
398
+ ### `doc`
399
+
400
+ The `doc:` namespace has the tools to generate documentation for your app, API documentation, guides. Documentation can also be stripped which is mainly useful for slimming your codebase, like if you're writing a Rails application for an embedded platform.
401
+
402
+ * `rake doc:app` generates documentation for your application in `doc/app`.
403
+ * `rake doc:guides` generates Rails guides in `doc/guides`.
404
+ * `rake doc:rails` generates API documentation for Rails in `doc/api`.
405
+
406
+ ### `notes`
407
+
408
+ `rake notes` will search through your code for comments beginning with FIXME, OPTIMIZE or TODO. The search is done in files with extension `.builder`, `.rb`, `.erb`, `.haml` and `.slim` for both default and custom annotations.
409
+
410
+ ```bash
411
+ $ rake notes
412
+ (in /home/foobar/commandsapp)
413
+ app/controllers/admin/users_controller.rb:
414
+ * [ 20] [TODO] any other way to do this?
415
+ * [132] [FIXME] high priority for next deploy
416
+
417
+ app/model/school.rb:
418
+ * [ 13] [OPTIMIZE] refactor this code to make it faster
419
+ * [ 17] [FIXME]
420
+ ```
421
+
422
+ If you are looking for a specific annotation, say FIXME, you can use `rake notes:fixme`. Note that you have to lower case the annotation's name.
423
+
424
+ ```bash
425
+ $ rake notes:fixme
426
+ (in /home/foobar/commandsapp)
427
+ app/controllers/admin/users_controller.rb:
428
+ * [132] high priority for next deploy
429
+
430
+ app/model/school.rb:
431
+ * [ 17]
432
+ ```
433
+
434
+ You can also use custom annotations in your code and list them using `rake notes:custom` by specifying the annotation using an environment variable `ANNOTATION`.
435
+
436
+ ```bash
437
+ $ rake notes:custom ANNOTATION=BUG
438
+ (in /home/foobar/commandsapp)
439
+ app/model/post.rb:
440
+ * [ 23] Have to fix this one before pushing!
441
+ ```
442
+
443
+ NOTE. When using specific annotations and custom annotations, the annotation name (FIXME, BUG etc) is not displayed in the output lines.
444
+
445
+ By default, `rake notes` will look in the `app`, `config`, `lib`, `bin` and `test` directories. If you would like to search other directories, you can provide them as a comma separated list in an environment variable `SOURCE_ANNOTATION_DIRECTORIES`.
446
+
447
+ ```bash
448
+ $ export SOURCE_ANNOTATION_DIRECTORIES='rspec,vendor'
449
+ $ rake notes
450
+ (in /home/foobar/commandsapp)
451
+ app/model/user.rb:
452
+ * [ 35] [FIXME] User should have a subscription at this point
453
+ rspec/model/user_spec.rb:
454
+ * [122] [TODO] Verify the user that has a subscription works
455
+ ```
456
+
457
+ ### `routes`
458
+
459
+ `rake routes` will list all of your defined routes, which is useful for tracking down routing problems in your app, or giving you a good overview of the URLs in an app you're trying to get familiar with.
460
+
461
+ ### `test`
462
+
463
+ INFO: A good description of unit testing in Rails is given in [A Guide to Testing Rails Applications](testing.html)
464
+
465
+ Rails comes with a test suite called `Test::Unit`. Rails owes its stability to the use of tests. The tasks available in the `test:` namespace helps in running the different tests you will hopefully write.
466
+
467
+ ### `tmp`
468
+
469
+ The `Rails.root/tmp` directory is, like the *nix /tmp directory, the holding place for temporary files like sessions (if you're using a file store for files), process id files, and cached actions.
470
+
471
+ The `tmp:` namespaced tasks will help you clear the `Rails.root/tmp` directory:
472
+
473
+ * `rake tmp:cache:clear` clears `tmp/cache`.
474
+ * `rake tmp:sessions:clear` clears `tmp/sessions`.
475
+ * `rake tmp:sockets:clear` clears `tmp/sockets`.
476
+ * `rake tmp:clear` clears all the three: cache, sessions and sockets.
477
+
478
+ ### Miscellaneous
479
+
480
+ * `rake stats` is great for looking at statistics on your code, displaying things like KLOCs (thousands of lines of code) and your code to test ratio.
481
+ * `rake secret` will give you a pseudo-random key to use for your session secret.
482
+ * `rake time:zones:all` lists all the timezones Rails knows about.
483
+
484
+ ### Custom Rake Tasks
485
+
486
+ Custom rake tasks have a `.rake` extension and are placed in `Rails.root/lib/tasks`.
487
+
488
+ ```ruby
489
+ desc "I am short, but comprehensive description for my cool task"
490
+ task task_name: [:prerequisite_task, :another_task_we_depend_on] do
491
+ # All your magic here
492
+ # Any valid Ruby code is allowed
493
+ end
494
+ ```
495
+
496
+ To pass arguments to your custom rake task:
497
+
498
+ ```ruby
499
+ task :task_name, [:arg_1] => [:pre_1, :pre_2] do |t, args|
500
+ # You can use args from here
501
+ end
502
+ ```
503
+
504
+ You can group tasks by placing them in namespaces:
505
+
506
+ ```ruby
507
+ namespace :db do
508
+ desc "This task does nothing"
509
+ task :nothing do
510
+ # Seriously, nothing
511
+ end
512
+ end
513
+ ```
514
+
515
+ Invocation of the tasks will look like:
516
+
517
+ ```bash
518
+ rake task_name
519
+ rake "task_name[value 1]" # entire argument string should be quoted
520
+ rake db:nothing
521
+ ```
522
+
523
+ NOTE: If your need to interact with your application models, perform database queries and so on, your task should depend on the `environment` task, which will load your application code.
524
+
525
+ The Rails Advanced Command Line
526
+ -------------------------------
527
+
528
+ More advanced use of the command line is focused around finding useful (even surprising at times) options in the utilities, and fitting those to your needs and specific work flow. Listed here are some tricks up Rails' sleeve.
529
+
530
+ ### Rails with Databases and SCM
531
+
532
+ When creating a new Rails application, you have the option to specify what kind of database and what kind of source code management system your application is going to use. This will save you a few minutes, and certainly many keystrokes.
533
+
534
+ Let's see what a `--git` option and a `--database=postgresql` option will do for us:
535
+
536
+ ```bash
537
+ $ mkdir gitapp
538
+ $ cd gitapp
539
+ $ git init
540
+ Initialized empty Git repository in .git/
541
+ $ rails new . --git --database=postgresql
542
+ exists
543
+ create app/controllers
544
+ create app/helpers
545
+ ...
546
+ ...
547
+ create tmp/cache
548
+ create tmp/pids
549
+ create Rakefile
550
+ add 'Rakefile'
551
+ create README.rdoc
552
+ add 'README.rdoc'
553
+ create app/controllers/application_controller.rb
554
+ add 'app/controllers/application_controller.rb'
555
+ create app/helpers/application_helper.rb
556
+ ...
557
+ create log/test.log
558
+ add 'log/test.log'
559
+ ```
560
+
561
+ We had to create the **gitapp** directory and initialize an empty git repository before Rails would add files it created to our repository. Let's see what it put in our database configuration:
562
+
563
+ ```bash
564
+ $ cat config/database.yml
565
+ # PostgreSQL. Versions 8.2 and up are supported.
566
+ #
567
+ # Install the pg driver:
568
+ # gem install pg
569
+ # On OS X with Homebrew:
570
+ # gem install pg -- --with-pg-config=/usr/local/bin/pg_config
571
+ # On OS X with MacPorts:
572
+ # gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config
573
+ # On Windows:
574
+ # gem install pg
575
+ # Choose the win32 build.
576
+ # Install PostgreSQL and put its /bin directory on your path.
577
+ #
578
+ # Configure Using Gemfile
579
+ # gem 'pg'
580
+ #
581
+ development:
582
+ adapter: postgresql
583
+ encoding: unicode
584
+ database: gitapp_development
585
+ pool: 5
586
+ username: gitapp
587
+ password:
588
+ ...
589
+ ...
590
+ ```
591
+
592
+ It also generated some lines in our database.yml configuration corresponding to our choice of PostgreSQL for database.
593
+
594
+ NOTE. The only catch with using the SCM options is that you have to make your application's directory first, then initialize your SCM, then you can run the `rails new` command to generate the basis of your app.