rails 4.2.11.3 → 5.0.0.beta1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (218) hide show
  1. checksums.yaml +5 -5
  2. data/README.md +11 -7
  3. metadata +38 -237
  4. data/guides/CHANGELOG.md +0 -113
  5. data/guides/Rakefile +0 -92
  6. data/guides/assets/images/akshaysurve.jpg +0 -0
  7. data/guides/assets/images/belongs_to.png +0 -0
  8. data/guides/assets/images/book_icon.gif +0 -0
  9. data/guides/assets/images/bullet.gif +0 -0
  10. data/guides/assets/images/chapters_icon.gif +0 -0
  11. data/guides/assets/images/check_bullet.gif +0 -0
  12. data/guides/assets/images/credits_pic_blank.gif +0 -0
  13. data/guides/assets/images/csrf.png +0 -0
  14. data/guides/assets/images/edge_badge.png +0 -0
  15. data/guides/assets/images/favicon.ico +0 -0
  16. data/guides/assets/images/feature_tile.gif +0 -0
  17. data/guides/assets/images/footer_tile.gif +0 -0
  18. data/guides/assets/images/fxn.png +0 -0
  19. data/guides/assets/images/getting_started/article_with_comments.png +0 -0
  20. data/guides/assets/images/getting_started/challenge.png +0 -0
  21. data/guides/assets/images/getting_started/confirm_dialog.png +0 -0
  22. data/guides/assets/images/getting_started/forbidden_attributes_for_new_article.png +0 -0
  23. data/guides/assets/images/getting_started/form_with_errors.png +0 -0
  24. data/guides/assets/images/getting_started/index_action_with_edit_link.png +0 -0
  25. data/guides/assets/images/getting_started/new_article.png +0 -0
  26. data/guides/assets/images/getting_started/rails_welcome.png +0 -0
  27. data/guides/assets/images/getting_started/routing_error_no_controller.png +0 -0
  28. data/guides/assets/images/getting_started/routing_error_no_route_matches.png +0 -0
  29. data/guides/assets/images/getting_started/show_action_for_articles.png +0 -0
  30. data/guides/assets/images/getting_started/template_is_missing_articles_new.png +0 -0
  31. data/guides/assets/images/getting_started/unknown_action_create_for_articles.png +0 -0
  32. data/guides/assets/images/getting_started/unknown_action_new_for_articles.png +0 -0
  33. data/guides/assets/images/grey_bullet.gif +0 -0
  34. data/guides/assets/images/habtm.png +0 -0
  35. data/guides/assets/images/has_many.png +0 -0
  36. data/guides/assets/images/has_many_through.png +0 -0
  37. data/guides/assets/images/has_one.png +0 -0
  38. data/guides/assets/images/has_one_through.png +0 -0
  39. data/guides/assets/images/header_backdrop.png +0 -0
  40. data/guides/assets/images/header_tile.gif +0 -0
  41. data/guides/assets/images/i18n/demo_html_safe.png +0 -0
  42. data/guides/assets/images/i18n/demo_localized_pirate.png +0 -0
  43. data/guides/assets/images/i18n/demo_translated_en.png +0 -0
  44. data/guides/assets/images/i18n/demo_translated_pirate.png +0 -0
  45. data/guides/assets/images/i18n/demo_translation_missing.png +0 -0
  46. data/guides/assets/images/i18n/demo_untranslated.png +0 -0
  47. data/guides/assets/images/icons/README +0 -5
  48. data/guides/assets/images/icons/callouts/1.png +0 -0
  49. data/guides/assets/images/icons/callouts/10.png +0 -0
  50. data/guides/assets/images/icons/callouts/11.png +0 -0
  51. data/guides/assets/images/icons/callouts/12.png +0 -0
  52. data/guides/assets/images/icons/callouts/13.png +0 -0
  53. data/guides/assets/images/icons/callouts/14.png +0 -0
  54. data/guides/assets/images/icons/callouts/15.png +0 -0
  55. data/guides/assets/images/icons/callouts/2.png +0 -0
  56. data/guides/assets/images/icons/callouts/3.png +0 -0
  57. data/guides/assets/images/icons/callouts/4.png +0 -0
  58. data/guides/assets/images/icons/callouts/5.png +0 -0
  59. data/guides/assets/images/icons/callouts/6.png +0 -0
  60. data/guides/assets/images/icons/callouts/7.png +0 -0
  61. data/guides/assets/images/icons/callouts/8.png +0 -0
  62. data/guides/assets/images/icons/callouts/9.png +0 -0
  63. data/guides/assets/images/icons/caution.png +0 -0
  64. data/guides/assets/images/icons/example.png +0 -0
  65. data/guides/assets/images/icons/home.png +0 -0
  66. data/guides/assets/images/icons/important.png +0 -0
  67. data/guides/assets/images/icons/next.png +0 -0
  68. data/guides/assets/images/icons/note.png +0 -0
  69. data/guides/assets/images/icons/prev.png +0 -0
  70. data/guides/assets/images/icons/tip.png +0 -0
  71. data/guides/assets/images/icons/up.png +0 -0
  72. data/guides/assets/images/icons/warning.png +0 -0
  73. data/guides/assets/images/nav_arrow.gif +0 -0
  74. data/guides/assets/images/oscardelben.jpg +0 -0
  75. data/guides/assets/images/polymorphic.png +0 -0
  76. data/guides/assets/images/radar.png +0 -0
  77. data/guides/assets/images/rails4_features.png +0 -0
  78. data/guides/assets/images/rails_guides_kindle_cover.jpg +0 -0
  79. data/guides/assets/images/rails_guides_logo.gif +0 -0
  80. data/guides/assets/images/rails_logo_remix.gif +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 +0 -59
  90. data/guides/assets/javascripts/jquery.min.js +0 -4
  91. data/guides/assets/javascripts/responsive-tables.js +0 -43
  92. data/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js +0 -59
  93. data/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js +0 -75
  94. data/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js +0 -59
  95. data/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js +0 -65
  96. data/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js +0 -100
  97. data/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js +0 -97
  98. data/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js +0 -91
  99. data/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js +0 -55
  100. data/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js +0 -41
  101. data/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js +0 -52
  102. data/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js +0 -67
  103. data/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js +0 -52
  104. data/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js +0 -57
  105. data/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js +0 -58
  106. data/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js +0 -72
  107. data/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js +0 -88
  108. data/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js +0 -33
  109. data/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js +0 -74
  110. data/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js +0 -64
  111. data/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js +0 -55
  112. data/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js +0 -94
  113. data/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js +0 -51
  114. data/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js +0 -66
  115. data/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js +0 -56
  116. data/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js +0 -69
  117. data/guides/assets/javascripts/syntaxhighlighter/shCore.js +0 -17
  118. data/guides/assets/stylesheets/fixes.css +0 -16
  119. data/guides/assets/stylesheets/kindle.css +0 -11
  120. data/guides/assets/stylesheets/main.css +0 -713
  121. data/guides/assets/stylesheets/print.css +0 -52
  122. data/guides/assets/stylesheets/reset.css +0 -43
  123. data/guides/assets/stylesheets/responsive-tables.css +0 -50
  124. data/guides/assets/stylesheets/style.css +0 -13
  125. data/guides/assets/stylesheets/syntaxhighlighter/shCore.css +0 -226
  126. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css +0 -328
  127. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css +0 -331
  128. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css +0 -339
  129. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css +0 -324
  130. data/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +0 -328
  131. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css +0 -324
  132. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css +0 -324
  133. data/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css +0 -324
  134. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css +0 -117
  135. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css +0 -120
  136. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css +0 -128
  137. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css +0 -113
  138. data/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +0 -117
  139. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css +0 -113
  140. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css +0 -113
  141. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css +0 -113
  142. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +0 -116
  143. data/guides/bug_report_templates/action_controller_gem.rb +0 -47
  144. data/guides/bug_report_templates/action_controller_master.rb +0 -54
  145. data/guides/bug_report_templates/active_record_gem.rb +0 -40
  146. data/guides/bug_report_templates/active_record_master.rb +0 -49
  147. data/guides/bug_report_templates/generic_gem.rb +0 -15
  148. data/guides/bug_report_templates/generic_master.rb +0 -26
  149. data/guides/rails_guides.rb +0 -63
  150. data/guides/rails_guides/generator.rb +0 -248
  151. data/guides/rails_guides/helpers.rb +0 -53
  152. data/guides/rails_guides/indexer.rb +0 -68
  153. data/guides/rails_guides/kindle.rb +0 -119
  154. data/guides/rails_guides/levenshtein.rb +0 -37
  155. data/guides/rails_guides/markdown.rb +0 -167
  156. data/guides/rails_guides/markdown/renderer.rb +0 -82
  157. data/guides/source/2_2_release_notes.md +0 -435
  158. data/guides/source/2_3_release_notes.md +0 -621
  159. data/guides/source/3_0_release_notes.md +0 -611
  160. data/guides/source/3_1_release_notes.md +0 -559
  161. data/guides/source/3_2_release_notes.md +0 -568
  162. data/guides/source/4_0_release_notes.md +0 -279
  163. data/guides/source/4_1_release_notes.md +0 -730
  164. data/guides/source/4_2_release_notes.md +0 -877
  165. data/guides/source/_license.html.erb +0 -2
  166. data/guides/source/_welcome.html.erb +0 -23
  167. data/guides/source/action_controller_overview.md +0 -1192
  168. data/guides/source/action_mailer_basics.md +0 -757
  169. data/guides/source/action_view_overview.md +0 -1561
  170. data/guides/source/active_job_basics.md +0 -339
  171. data/guides/source/active_model_basics.md +0 -554
  172. data/guides/source/active_record_basics.md +0 -374
  173. data/guides/source/active_record_callbacks.md +0 -413
  174. data/guides/source/active_record_migrations.md +0 -1018
  175. data/guides/source/active_record_postgresql.md +0 -433
  176. data/guides/source/active_record_querying.md +0 -1781
  177. data/guides/source/active_record_validations.md +0 -1179
  178. data/guides/source/active_support_core_extensions.md +0 -3856
  179. data/guides/source/active_support_instrumentation.md +0 -488
  180. data/guides/source/api_documentation_guidelines.md +0 -361
  181. data/guides/source/asset_pipeline.md +0 -1304
  182. data/guides/source/association_basics.md +0 -2245
  183. data/guides/source/autoloading_and_reloading_constants.md +0 -1311
  184. data/guides/source/caching_with_rails.md +0 -379
  185. data/guides/source/command_line.md +0 -625
  186. data/guides/source/configuring.md +0 -1070
  187. data/guides/source/contributing_to_ruby_on_rails.md +0 -628
  188. data/guides/source/credits.html.erb +0 -80
  189. data/guides/source/debugging_rails_applications.md +0 -861
  190. data/guides/source/development_dependencies_install.md +0 -289
  191. data/guides/source/documents.yaml +0 -205
  192. data/guides/source/engines.md +0 -1412
  193. data/guides/source/form_helpers.md +0 -1024
  194. data/guides/source/generators.md +0 -676
  195. data/guides/source/getting_started.md +0 -2086
  196. data/guides/source/i18n.md +0 -1087
  197. data/guides/source/index.html.erb +0 -28
  198. data/guides/source/initialization.md +0 -704
  199. data/guides/source/kindle/copyright.html.erb +0 -1
  200. data/guides/source/kindle/layout.html.erb +0 -27
  201. data/guides/source/kindle/rails_guides.opf.erb +0 -52
  202. data/guides/source/kindle/toc.html.erb +0 -24
  203. data/guides/source/kindle/toc.ncx.erb +0 -64
  204. data/guides/source/kindle/welcome.html.erb +0 -5
  205. data/guides/source/layout.html.erb +0 -140
  206. data/guides/source/layouts_and_rendering.md +0 -1226
  207. data/guides/source/maintenance_policy.md +0 -78
  208. data/guides/source/nested_model_forms.md +0 -228
  209. data/guides/source/plugins.md +0 -444
  210. data/guides/source/rails_application_templates.md +0 -266
  211. data/guides/source/rails_on_rack.md +0 -335
  212. data/guides/source/routing.md +0 -1155
  213. data/guides/source/ruby_on_rails_guides_guidelines.md +0 -127
  214. data/guides/source/security.md +0 -1024
  215. data/guides/source/testing.md +0 -1132
  216. data/guides/source/upgrading_ruby_on_rails.md +0 -1186
  217. data/guides/source/working_with_javascript_in_rails.md +0 -407
  218. data/guides/w3c_validator.rb +0 -97
@@ -1,379 +0,0 @@
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 and action caching (moved to separate gems as of Rails 4).
9
- * Fragment caching.
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). See [DHH's key-based cache expiration overview](http://signalvnoise.com/posts/3113-how-key-based-cache-expiration-works) for the newly-preferred method.
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). See [DHH's key-based cache expiration overview](http://signalvnoise.com/posts/3113-how-key-based-cache-expiration-works) for the newly-preferred method.
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
-
108
- If you want to cache a fragment under certain condition you can use `cache_if` or `cache_unless`
109
-
110
- ```erb
111
- <% cache_if (condition, cache_key_for_products) do %>
112
- All available products:
113
- <% end %>
114
- ```
115
-
116
- You can also use an Active Record model as the cache key:
117
-
118
- ```erb
119
- <% Product.all.each do |p| %>
120
- <% cache(p) do %>
121
- <%= link_to p.name, product_url(p) %>
122
- <% end %>
123
- <% end %>
124
- ```
125
-
126
- 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.
127
-
128
- You can also combine the two schemes which is called "Russian Doll Caching":
129
-
130
- ```erb
131
- <% cache(cache_key_for_products) do %>
132
- All available products:
133
- <% Product.all.each do |p| %>
134
- <% cache(p) do %>
135
- <%= link_to p.name, product_url(p) %>
136
- <% end %>
137
- <% end %>
138
- <% end %>
139
- ```
140
-
141
- 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.
142
-
143
- ### Low-Level Caching
144
-
145
- Sometimes you need to cache a particular value or query result, instead of caching view fragments. Rails caching mechanism works great for storing __any__ kind of information.
146
-
147
- The most efficient way to implement low-level caching is using the `Rails.cache.fetch` method. This method does both reading and writing to the cache. When passed only a single argument, the key is fetched and value from the cache is returned. If a block is passed, the result of the block will be cached to the given key and the result is returned.
148
-
149
- Consider the following example. An application has a `Product` model with an instance method that looks up the product’s price on a competing website. The data returned by this method would be perfect for low-level caching:
150
-
151
- ```ruby
152
- class Product < ActiveRecord::Base
153
- def competing_price
154
- Rails.cache.fetch("#{cache_key}/competing_price", expires_in: 12.hours) do
155
- Competitor::API.find_price(id)
156
- end
157
- end
158
- end
159
- ```
160
-
161
- NOTE: Notice that in this example we used `cache_key` method, so the resulting cache-key will be something like `products/233-20140225082222765838000/competing_price`. `cache_key` generates a string based on the model’s `id` and `updated_at` attributes. This is a common convention and has the benefit of invalidating the cache whenever the product is updated. In general, when you use low-level caching for instance level information, you need to generate a cache key.
162
-
163
- ### SQL Caching
164
-
165
- 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.
166
-
167
- For example:
168
-
169
- ```ruby
170
- class ProductsController < ApplicationController
171
-
172
- def index
173
- # Run a find query
174
- @products = Product.all
175
-
176
- ...
177
-
178
- # Run the same query again
179
- @products = Product.all
180
- end
181
-
182
- end
183
- ```
184
-
185
- Cache Stores
186
- ------------
187
-
188
- Rails provides different stores for the cached data created by **action** and **fragment** caches.
189
-
190
- TIP: Page caches are always stored on disk.
191
-
192
- ### Configuration
193
-
194
- 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.
195
-
196
- ```ruby
197
- config.cache_store = :memory_store
198
- ```
199
-
200
- NOTE: Alternatively, you can call `ActionController::Base.cache_store` outside of a configuration block.
201
-
202
- You can access the cache by calling `Rails.cache`.
203
-
204
- ### ActiveSupport::Cache::Store
205
-
206
- 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.
207
-
208
- 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.
209
-
210
- 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.
211
-
212
- * `: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.
213
-
214
- * `: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.
215
-
216
- * `: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.
217
-
218
- * `:expires_in` - This option sets an expiration time in seconds for the cache entry when it will be automatically removed from the cache.
219
-
220
- * `: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.
221
-
222
- ### ActiveSupport::Cache::MemoryStore
223
-
224
- 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.
225
-
226
- ```ruby
227
- config.cache_store = :memory_store, { size: 64.megabytes }
228
- ```
229
-
230
- 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.
231
-
232
- ### ActiveSupport::Cache::FileStore
233
-
234
- 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.
235
-
236
- ```ruby
237
- config.cache_store = :file_store, "/path/to/cache/directory"
238
- ```
239
-
240
- 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.
241
-
242
- Note that the cache will grow until the disk is full unless you periodically clear out old entries.
243
-
244
- This is the default cache store implementation.
245
-
246
- ### ActiveSupport::Cache::MemCacheStore
247
-
248
- 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 high performance and redundancy.
249
-
250
- 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.
251
-
252
- 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.
253
-
254
- ```ruby
255
- config.cache_store = :mem_cache_store, "cache-1.example.com", "cache-2.example.com"
256
- ```
257
-
258
- ### ActiveSupport::Cache::EhcacheStore
259
-
260
- 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.
261
-
262
- ```ruby
263
- config.cache_store = :ehcache_store
264
- ```
265
-
266
- 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).
267
-
268
- 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:
269
-
270
- | Property | Argument Type | Description |
271
- | --------------------------- | ------------------- | ----------------------------------------------------------- |
272
- | elementEvictionData | ElementEvictionData | Sets this element's eviction data instance. |
273
- | eternal | boolean | Sets whether the element is eternal. |
274
- | timeToIdle, tti | int | Sets time to idle |
275
- | timeToLive, ttl, expires_in | int | Sets time to Live |
276
- | version | long | Sets the version attribute of the ElementAttributes object. |
277
-
278
- These options are passed to the `write` method as Hash options using either camelCase or underscore notation, as in the following examples:
279
-
280
- ```ruby
281
- Rails.cache.write('key', 'value', time_to_idle: 60.seconds, timeToLive: 600.seconds)
282
- caches_action :index, expires_in: 60.seconds, unless_exist: true
283
- ```
284
-
285
- For more information about Ehcache, see [http://ehcache.org/](http://ehcache.org/) .
286
- For more information about Ehcache for JRuby and Rails, see [http://ehcache.org/documentation/jruby.html](http://ehcache.org/documentation/jruby.html)
287
-
288
- ### ActiveSupport::Cache::NullStore
289
-
290
- 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.
291
-
292
- ```ruby
293
- config.cache_store = :null_store
294
- ```
295
-
296
- ### Custom Cache Stores
297
-
298
- 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.
299
-
300
- To use a custom cache store, simple set the cache store to a new instance of the class.
301
-
302
- ```ruby
303
- config.cache_store = MyCacheStore.new
304
- ```
305
-
306
- ### Cache Keys
307
-
308
- 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.
309
-
310
- You can use Hashes and Arrays of values as cache keys.
311
-
312
- ```ruby
313
- # This is a legal cache key
314
- Rails.cache.read(site: "mysite", owners: [owner_1, owner_2])
315
- ```
316
-
317
- 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.
318
-
319
- Conditional GET support
320
- -----------------------
321
-
322
- 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.
323
-
324
- 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.
325
-
326
- 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:
327
-
328
- ```ruby
329
- class ProductsController < ApplicationController
330
-
331
- def show
332
- @product = Product.find(params[:id])
333
-
334
- # If the request is stale according to the given timestamp and etag value
335
- # (i.e. it needs to be processed again) then execute this block
336
- if stale?(last_modified: @product.updated_at.utc, etag: @product.cache_key)
337
- respond_to do |wants|
338
- # ... normal response processing
339
- end
340
- end
341
-
342
- # If the request is fresh (i.e. it's not modified) then you don't need to do
343
- # anything. The default render checks for this using the parameters
344
- # used in the previous call to stale? and will automatically send a
345
- # :not_modified. So that's it, you're done.
346
- end
347
- end
348
- ```
349
-
350
- Instead of an 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`:
351
-
352
- ```ruby
353
- class ProductsController < ApplicationController
354
- def show
355
- @product = Product.find(params[:id])
356
-
357
- if stale?(@product)
358
- respond_to do |wants|
359
- # ... normal response processing
360
- end
361
- end
362
- end
363
- end
364
- ```
365
-
366
- 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`:
367
-
368
- ```ruby
369
- class ProductsController < ApplicationController
370
-
371
- # This will automatically send back a :not_modified if the request is fresh,
372
- # and will render the default template (product.*) if it's stale.
373
-
374
- def show
375
- @product = Product.find(params[:id])
376
- fresh_when last_modified: @product.published_at.utc, etag: @product
377
- end
378
- end
379
- ```
@@ -1,625 +0,0 @@
1
- The Rails Command Line
2
- ======================
3
-
4
- After reading this guide, you will know:
5
-
6
- * How to create a Rails application.
7
- * How to generate models, controllers, database migrations, and unit tests.
8
- * How to start a development server.
9
- * How to experiment with objects through an interactive shell.
10
-
11
- --------------------------------------------------------------------------------
12
-
13
- NOTE: This tutorial assumes you have basic Rails knowledge from reading the [Getting Started with Rails Guide](getting_started.html).
14
-
15
- Command Line Basics
16
- -------------------
17
-
18
- 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:
19
-
20
- * `rails console`
21
- * `rails server`
22
- * `rake`
23
- * `rails generate`
24
- * `rails dbconsole`
25
- * `rails new app_name`
26
-
27
- All commands can run with ```-h or --help``` to list more information.
28
-
29
- Let's create a simple Rails application to step through each of these commands in context.
30
-
31
- ### `rails new`
32
-
33
- The first thing we'll want to do is create a new Rails application by running the `rails new` command after installing Rails.
34
-
35
- INFO: You can install the rails gem by typing `gem install rails`, if you don't have it already.
36
-
37
- ```bash
38
- $ rails new commandsapp
39
- create
40
- create README.rdoc
41
- create Rakefile
42
- create config.ru
43
- create .gitignore
44
- create Gemfile
45
- create app
46
- ...
47
- create tmp/cache
48
- ...
49
- run bundle install
50
- ```
51
-
52
- 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.
53
-
54
- ### `rails server`
55
-
56
- 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.
57
-
58
- With no further work, `rails server` will run our new shiny Rails app:
59
-
60
- ```bash
61
- $ cd commandsapp
62
- $ bin/rails server
63
- => Booting WEBrick
64
- => Rails 4.2.0 application starting in development on http://localhost:3000
65
- => Call with -d to detach
66
- => Ctrl-C to shutdown server
67
- [2013-08-07 02:00:01] INFO WEBrick 1.3.1
68
- [2013-08-07 02:00:01] INFO ruby 2.0.0 (2013-06-27) [x86_64-darwin11.2.0]
69
- [2013-08-07 02:00:01] INFO WEBrick::HTTPServer#start: pid=69680 port=3000
70
- ```
71
-
72
- 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.
73
-
74
- INFO: You can also use the alias "s" to start the server: `rails s`.
75
-
76
- The server can be run on a different port using the `-p` option. The default development environment can be changed using `-e`.
77
-
78
- ```bash
79
- $ bin/rails server -e production -p 4000
80
- ```
81
-
82
- The `-b` option binds Rails to the specified IP, by default it is localhost. You can run a server as a daemon by passing a `-d` option.
83
-
84
- ### `rails generate`
85
-
86
- The `rails generate` command uses templates to create a whole lot of things. Running `rails generate` by itself gives a list of available generators:
87
-
88
- INFO: You can also use the alias "g" to invoke the generator command: `rails g`.
89
-
90
- ```bash
91
- $ bin/rails generate
92
- Usage: rails generate GENERATOR [args] [options]
93
-
94
- ...
95
- ...
96
-
97
- Please choose a generator below.
98
-
99
- Rails:
100
- assets
101
- controller
102
- generator
103
- ...
104
- ...
105
- ```
106
-
107
- NOTE: You can install more generators through generator gems, portions of plugins you'll undoubtedly install, and you can even create your own!
108
-
109
- Using generators will save you a large amount of time by writing **boilerplate code**, code that is necessary for the app to work.
110
-
111
- Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator:
112
-
113
- 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`.
114
-
115
- ```bash
116
- $ bin/rails generate controller
117
- Usage: rails generate controller NAME [action action] [options]
118
-
119
- ...
120
- ...
121
-
122
- Description:
123
- ...
124
-
125
- To create a controller within a module, specify the controller name as a path like 'parent_module/controller_name'.
126
-
127
- ...
128
-
129
- Example:
130
- `rails generate controller CreditCards open debit credit close`
131
-
132
- Credit card controller with URLs like /credit_cards/debit.
133
- Controller: app/controllers/credit_cards_controller.rb
134
- Test: test/controllers/credit_cards_controller_test.rb
135
- Views: app/views/credit_cards/debit.html.erb [...]
136
- Helper: app/helpers/credit_cards_helper.rb
137
- ```
138
-
139
- 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.
140
-
141
- ```bash
142
- $ bin/rails generate controller Greetings hello
143
- create app/controllers/greetings_controller.rb
144
- route get "greetings/hello"
145
- invoke erb
146
- create app/views/greetings
147
- create app/views/greetings/hello.html.erb
148
- invoke test_unit
149
- create test/controllers/greetings_controller_test.rb
150
- invoke helper
151
- create app/helpers/greetings_helper.rb
152
- invoke assets
153
- invoke coffee
154
- create app/assets/javascripts/greetings.js.coffee
155
- invoke scss
156
- create app/assets/stylesheets/greetings.css.scss
157
- ```
158
-
159
- 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.
160
-
161
- Check out the controller and modify it a little (in `app/controllers/greetings_controller.rb`):
162
-
163
- ```ruby
164
- class GreetingsController < ApplicationController
165
- def hello
166
- @message = "Hello, how are you today?"
167
- end
168
- end
169
- ```
170
-
171
- Then the view, to display our message (in `app/views/greetings/hello.html.erb`):
172
-
173
- ```erb
174
- <h1>A Greeting for You!</h1>
175
- <p><%= @message %></p>
176
- ```
177
-
178
- Fire up your server using `rails server`.
179
-
180
- ```bash
181
- $ bin/rails server
182
- => Booting WEBrick...
183
- ```
184
-
185
- The URL will be [http://localhost:3000/greetings/hello](http://localhost:3000/greetings/hello).
186
-
187
- 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.
188
-
189
- Rails comes with a generator for data models too.
190
-
191
- ```bash
192
- $ bin/rails generate model
193
- Usage:
194
- rails generate model NAME [field[:type][:index] field[:type][:index]] [options]
195
-
196
- ...
197
-
198
- Active Record options:
199
- [--migration] # Indicates when to generate migration
200
- # Default: true
201
-
202
- ...
203
-
204
- Description:
205
- Create rails files for model generator.
206
- ```
207
-
208
- 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.
209
-
210
- 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.
211
-
212
- We will set up a simple resource called "HighScore" that will keep track of our highest score on video games we play.
213
-
214
- ```bash
215
- $ bin/rails generate scaffold HighScore game:string score:integer
216
- invoke active_record
217
- create db/migrate/20130717151933_create_high_scores.rb
218
- create app/models/high_score.rb
219
- invoke test_unit
220
- create test/models/high_score_test.rb
221
- create test/fixtures/high_scores.yml
222
- invoke resource_route
223
- route resources :high_scores
224
- invoke scaffold_controller
225
- create app/controllers/high_scores_controller.rb
226
- invoke erb
227
- create app/views/high_scores
228
- create app/views/high_scores/index.html.erb
229
- create app/views/high_scores/edit.html.erb
230
- create app/views/high_scores/show.html.erb
231
- create app/views/high_scores/new.html.erb
232
- create app/views/high_scores/_form.html.erb
233
- invoke test_unit
234
- create test/controllers/high_scores_controller_test.rb
235
- invoke helper
236
- create app/helpers/high_scores_helper.rb
237
- invoke jbuilder
238
- create app/views/high_scores/index.json.jbuilder
239
- create app/views/high_scores/show.json.jbuilder
240
- invoke assets
241
- invoke coffee
242
- create app/assets/javascripts/high_scores.js.coffee
243
- invoke scss
244
- create app/assets/stylesheets/high_scores.css.scss
245
- invoke scss
246
- identical app/assets/stylesheets/scaffolds.css.scss
247
- ```
248
-
249
- 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.
250
-
251
- The migration requires that we **migrate**, that is, run some Ruby code (living in that `20130717151933_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.
252
-
253
- ```bash
254
- $ bin/rake db:migrate
255
- == CreateHighScores: migrating ===============================================
256
- -- create_table(:high_scores)
257
- -> 0.0017s
258
- == CreateHighScores: migrated (0.0019s) ======================================
259
- ```
260
-
261
- 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.
262
-
263
- Let's see the interface Rails created for us.
264
-
265
- ```bash
266
- $ bin/rails server
267
- ```
268
-
269
- 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!)
270
-
271
- ### `rails console`
272
-
273
- 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.
274
-
275
- INFO: You can also use the alias "c" to invoke the console: `rails c`.
276
-
277
- You can specify the environment in which the `console` command should operate.
278
-
279
- ```bash
280
- $ bin/rails console staging
281
- ```
282
-
283
- If you wish to test out some code without changing any data, you can do that by invoking `rails console --sandbox`.
284
-
285
- ```bash
286
- $ bin/rails console --sandbox
287
- Loading development environment in sandbox (Rails 4.2.0)
288
- Any modifications you make will be rolled back on exit
289
- irb(main):001:0>
290
- ```
291
-
292
- #### The app and helper objects
293
-
294
- Inside the `rails console` you have access to the `app` and `helper` instances.
295
-
296
- With the `app` method you can access url and path helpers, as well as do requests.
297
-
298
- ```bash
299
- >> app.root_path
300
- => "/"
301
-
302
- >> app.get _
303
- Started GET "/" for 127.0.0.1 at 2014-06-19 10:41:57 -0300
304
- ...
305
- ```
306
-
307
- With the `helper` method it is possible to access Rails and your application's helpers.
308
-
309
- ```bash
310
- >> helper.time_ago_in_words 30.days.ago
311
- => "about 1 month"
312
-
313
- >> helper.my_custom_helper
314
- => "my custom helper"
315
- ```
316
-
317
- ### `rails dbconsole`
318
-
319
- `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.
320
-
321
- INFO: You can also use the alias "db" to invoke the dbconsole: `rails db`.
322
-
323
- ### `rails runner`
324
-
325
- `runner` runs Ruby code in the context of Rails non-interactively. For instance:
326
-
327
- ```bash
328
- $ bin/rails runner "Model.long_running_method"
329
- ```
330
-
331
- INFO: You can also use the alias "r" to invoke the runner: `rails r`.
332
-
333
- You can specify the environment in which the `runner` command should operate using the `-e` switch.
334
-
335
- ```bash
336
- $ bin/rails runner -e staging "Model.long_running_method"
337
- ```
338
-
339
- ### `rails destroy`
340
-
341
- Think of `destroy` as the opposite of `generate`. It'll figure out what generate did, and undo it.
342
-
343
- INFO: You can also use the alias "d" to invoke the destroy command: `rails d`.
344
-
345
- ```bash
346
- $ bin/rails generate model Oops
347
- invoke active_record
348
- create db/migrate/20120528062523_create_oops.rb
349
- create app/models/oops.rb
350
- invoke test_unit
351
- create test/models/oops_test.rb
352
- create test/fixtures/oops.yml
353
- ```
354
- ```bash
355
- $ bin/rails destroy model Oops
356
- invoke active_record
357
- remove db/migrate/20120528062523_create_oops.rb
358
- remove app/models/oops.rb
359
- invoke test_unit
360
- remove test/models/oops_test.rb
361
- remove test/fixtures/oops.yml
362
- ```
363
-
364
- Rake
365
- ----
366
-
367
- 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.
368
-
369
- 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.
370
-
371
- To get the full backtrace for running rake task you can pass the option ```--trace``` to command line, for example ```rake db:create --trace```.
372
-
373
- ```bash
374
- $ bin/rake --tasks
375
- rake about # List versions of all Rails frameworks and the environment
376
- rake assets:clean # Remove old compiled assets
377
- rake assets:clobber # Remove compiled assets
378
- rake assets:precompile # Compile all the assets named in config.assets.precompile
379
- rake db:create # Create the database from config/database.yml for the current Rails.env
380
- ...
381
- rake log:clear # Truncates all *.log files in log/ to zero bytes (specify which logs with LOGS=test,development)
382
- rake middleware # Prints out your Rack middleware stack
383
- ...
384
- rake tmp:clear # Clear session, cache, and socket files from tmp/ (narrow w/ tmp:sessions:clear, tmp:cache:clear, tmp:sockets:clear)
385
- rake tmp:create # Creates tmp directories for sessions, cache, sockets, and pids
386
- ```
387
- INFO: You can also use ```rake -T``` to get the list of tasks.
388
-
389
- ### `about`
390
-
391
- `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.
392
-
393
- ```bash
394
- $ bin/rake about
395
- About your application's environment
396
- Rails version 4.2.0
397
- Ruby version 1.9.3 (x86_64-linux)
398
- RubyGems version 1.3.6
399
- Rack version 1.3
400
- JavaScript Runtime Node.js (V8)
401
- Middleware Rack::Sendfile, ActionDispatch::Static, Rack::Lock, #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x007ffd131a7c88>, 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::CookieStore, ActionDispatch::Flash, ActionDispatch::ParamsParser, Rack::Head, Rack::ConditionalGet, Rack::ETag
402
- Application root /home/foobar/commandsapp
403
- Environment development
404
- Database adapter sqlite3
405
- Database schema version 20110805173523
406
- ```
407
-
408
- ### `assets`
409
-
410
- You can precompile the assets in `app/assets` using `rake assets:precompile`, and remove older compiled assets using `rake assets:clean`. The `assets:clean` task allows for rolling deploys that may still be linking to an old asset while the new assets are being built.
411
-
412
- If you want to clear `public/assets` completely, you can use `rake assets:clobber`.
413
-
414
- ### `db`
415
-
416
- 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.
417
-
418
- More information about migrations can be found in the [Migrations](migrations.html) guide.
419
-
420
- ### `doc`
421
-
422
- 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.
423
-
424
- * `rake doc:app` generates documentation for your application in `doc/app`.
425
- * `rake doc:guides` generates Rails guides in `doc/guides`.
426
- * `rake doc:rails` generates API documentation for Rails in `doc/api`.
427
-
428
- ### `notes`
429
-
430
- `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`, `.rake`, `.yml`, `.yaml`, `.ruby`, `.css`, `.js` and `.erb` for both default and custom annotations.
431
-
432
- ```bash
433
- $ bin/rake notes
434
- (in /home/foobar/commandsapp)
435
- app/controllers/admin/users_controller.rb:
436
- * [ 20] [TODO] any other way to do this?
437
- * [132] [FIXME] high priority for next deploy
438
-
439
- app/models/school.rb:
440
- * [ 13] [OPTIMIZE] refactor this code to make it faster
441
- * [ 17] [FIXME]
442
- ```
443
-
444
- You can add support for new file extensions using `config.annotations.register_extensions` option, which receives a list of the extensions with its corresponding regex to match it up.
445
-
446
- ```ruby
447
- config.annotations.register_extensions("scss", "sass", "less") { |annotation| /\/\/\s*(#{annotation}):?\s*(.*)$/ }
448
- ```
449
-
450
- 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.
451
-
452
- ```bash
453
- $ bin/rake notes:fixme
454
- (in /home/foobar/commandsapp)
455
- app/controllers/admin/users_controller.rb:
456
- * [132] high priority for next deploy
457
-
458
- app/models/school.rb:
459
- * [ 17]
460
- ```
461
-
462
- 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`.
463
-
464
- ```bash
465
- $ bin/rake notes:custom ANNOTATION=BUG
466
- (in /home/foobar/commandsapp)
467
- app/models/article.rb:
468
- * [ 23] Have to fix this one before pushing!
469
- ```
470
-
471
- NOTE. When using specific annotations and custom annotations, the annotation name (FIXME, BUG etc) is not displayed in the output lines.
472
-
473
- 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`.
474
-
475
- ```bash
476
- $ export SOURCE_ANNOTATION_DIRECTORIES='spec,vendor'
477
- $ bin/rake notes
478
- (in /home/foobar/commandsapp)
479
- app/models/user.rb:
480
- * [ 35] [FIXME] User should have a subscription at this point
481
- spec/models/user_spec.rb:
482
- * [122] [TODO] Verify the user that has a subscription works
483
- ```
484
-
485
- ### `routes`
486
-
487
- `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.
488
-
489
- ### `test`
490
-
491
- INFO: A good description of unit testing in Rails is given in [A Guide to Testing Rails Applications](testing.html)
492
-
493
- Rails comes with a test suite called Minitest. 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.
494
-
495
- ### `tmp`
496
-
497
- 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 sessions), process id files, and cached actions.
498
-
499
- The `tmp:` namespaced tasks will help you clear and create the `Rails.root/tmp` directory:
500
-
501
- * `rake tmp:cache:clear` clears `tmp/cache`.
502
- * `rake tmp:sessions:clear` clears `tmp/sessions`.
503
- * `rake tmp:sockets:clear` clears `tmp/sockets`.
504
- * `rake tmp:clear` clears all the three: cache, sessions and sockets.
505
- * `rake tmp:create` creates tmp directories for sessions, cache, sockets, and pids.
506
-
507
- ### Miscellaneous
508
-
509
- * `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.
510
- * `rake secret` will give you a pseudo-random key to use for your session secret.
511
- * `rake time:zones:all` lists all the timezones Rails knows about.
512
-
513
- ### Custom Rake Tasks
514
-
515
- Custom rake tasks have a `.rake` extension and are placed in
516
- `Rails.root/lib/tasks`. You can create these custom rake tasks with the
517
- `bin/rails generate task` command.
518
-
519
- ```ruby
520
- desc "I am short, but comprehensive description for my cool task"
521
- task task_name: [:prerequisite_task, :another_task_we_depend_on] do
522
- # All your magic here
523
- # Any valid Ruby code is allowed
524
- end
525
- ```
526
-
527
- To pass arguments to your custom rake task:
528
-
529
- ```ruby
530
- task :task_name, [:arg_1] => [:pre_1, :pre_2] do |t, args|
531
- # You can use args from here
532
- end
533
- ```
534
-
535
- You can group tasks by placing them in namespaces:
536
-
537
- ```ruby
538
- namespace :db do
539
- desc "This task does nothing"
540
- task :nothing do
541
- # Seriously, nothing
542
- end
543
- end
544
- ```
545
-
546
- Invocation of the tasks will look like:
547
-
548
- ```bash
549
- $ bin/rake task_name
550
- $ bin/rake "task_name[value 1]" # entire argument string should be quoted
551
- $ bin/rake db:nothing
552
- ```
553
-
554
- 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.
555
-
556
- The Rails Advanced Command Line
557
- -------------------------------
558
-
559
- 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.
560
-
561
- ### Rails with Databases and SCM
562
-
563
- 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.
564
-
565
- Let's see what a `--git` option and a `--database=postgresql` option will do for us:
566
-
567
- ```bash
568
- $ mkdir gitapp
569
- $ cd gitapp
570
- $ git init
571
- Initialized empty Git repository in .git/
572
- $ rails new . --git --database=postgresql
573
- exists
574
- create app/controllers
575
- create app/helpers
576
- ...
577
- ...
578
- create tmp/cache
579
- create tmp/pids
580
- create Rakefile
581
- add 'Rakefile'
582
- create README.rdoc
583
- add 'README.rdoc'
584
- create app/controllers/application_controller.rb
585
- add 'app/controllers/application_controller.rb'
586
- create app/helpers/application_helper.rb
587
- ...
588
- create log/test.log
589
- add 'log/test.log'
590
- ```
591
-
592
- 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:
593
-
594
- ```bash
595
- $ cat config/database.yml
596
- # PostgreSQL. Versions 8.2 and up are supported.
597
- #
598
- # Install the pg driver:
599
- # gem install pg
600
- # On OS X with Homebrew:
601
- # gem install pg -- --with-pg-config=/usr/local/bin/pg_config
602
- # On OS X with MacPorts:
603
- # gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config
604
- # On Windows:
605
- # gem install pg
606
- # Choose the win32 build.
607
- # Install PostgreSQL and put its /bin directory on your path.
608
- #
609
- # Configure Using Gemfile
610
- # gem 'pg'
611
- #
612
- development:
613
- adapter: postgresql
614
- encoding: unicode
615
- database: gitapp_development
616
- pool: 5
617
- username: gitapp
618
- password:
619
- ...
620
- ...
621
- ```
622
-
623
- It also generated some lines in our database.yml configuration corresponding to our choice of PostgreSQL for database.
624
-
625
- 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.