Froze rails gems
[depot.git] / vendor / rails / railties / doc / guides / source / caching_with_rails.txt
1 Caching with Rails: An overview
2 ===============================
3
4 Everyone caches. This guide will teach you what you need to know about
5 avoiding that expensive round-trip to your database and returning what you
6 need to return to those hungry web clients in the shortest time possible.
7
8 == Basic Caching
9
10 This is an introduction to the three types of caching techniques that Rails
11 provides by default without the use of any third party plugins.
12
13 To get started make sure config.action_controller.perform_caching is set
14 to true for your environment. This flag is normally set in the
15 corresponding config/environments/*.rb and caching is disabled by default
16 there for development and test, and enabled for production.
17
18 [source, ruby]
19 -----------------------------------------------------
20 config.action_controller.perform_caching = true
21 -----------------------------------------------------
22
23 === Page Caching
24
25 Page caching is a Rails mechanism which allows the request for a generated
26 page to be fulfilled by the webserver, without ever having to go through the
27 Rails stack at all. Obviously, this is super-fast. Unfortunately, it can't be
28 applied to every situation (such as pages that need authentication) and since
29 the webserver is literally just serving a file from the filesystem, cache
30 expiration is an issue that needs to be dealt with.
31
32 So, how do you enable this super-fast cache behavior? Simple, let's say you
33 have a controller called ProductsController and a 'list' action that lists all
34 the products
35
36 [source, ruby]
37 -----------------------------------------------------
38 class ProductsController < ActionController
39
40 caches_page :index
41
42 def index; end
43
44 end
45 -----------------------------------------------------
46
47 The first time anyone requests products/index, Rails will generate a file
48 called index.html and the webserver will then look for that file before it
49 passes the next request for products/index to your Rails application.
50
51 By default, the page cache directory is set to Rails.public_path (which is
52 usually set to RAILS_ROOT + "/public") and this can be configured by
53 changing the configuration setting ActionController::Base.page_cache_directory. Changing the
54 default from /public helps avoid naming conflicts, since you may want to
55 put other static html in /public, but changing this will require web
56 server reconfiguration to let the web server know where to serve the
57 cached files from.
58
59 The Page Caching mechanism will automatically add a .html exxtension to
60 requests for pages that do not have an extension to make it easy for the
61 webserver to find those pages and this can be configured by changing the
62 configuration setting ActionController::Base.page_cache_extension.
63
64 In order to expire this page when a new product is added we could extend our
65 example controler like this:
66
67 [source, ruby]
68 -----------------------------------------------------
69 class ProductsController < ActionController
70
71 caches_page :list
72
73 def list; end
74
75 def create
76 expire_page :action => :list
77 end
78
79 end
80 -----------------------------------------------------
81
82 If you want a more complicated expiration scheme, you can use cache sweepers
83 to expire cached objects when things change. This is covered in the section on Sweepers.
84
85 [More: caching paginated results? more examples? Walk-through of page caching?]
86
87 === Action Caching
88
89 One of the issues with Page Caching is that you cannot use it for pages that
90 require to restrict access somehow. This is where Action Caching comes in.
91 Action Caching works like Page Caching except for the fact that the incoming
92 web request does go from the webserver to the Rails stack and Action Pack so
93 that before filters can be run on it before the cache is served, so that
94 authentication and other restrictions can be used while still serving the
95 result of the output from a cached copy.
96
97 Clearing the cache works in the exact same way as with Page Caching.
98
99 Let's say you only wanted authenticated users to edit or create a Product
100 object, but still cache those pages:
101
102 [source, ruby]
103 -----------------------------------------------------
104 class ProductsController < ActionController
105
106 before_filter :authenticate, :only => [ :edit, :create ]
107 caches_page :list
108 caches_action :edit
109
110 def list; end
111
112 def create
113 expire_page :action => :list
114 expire_action :action => :edit
115 end
116
117 def edit; end
118
119 end
120 -----------------------------------------------------
121
122 And you can also use :if (or :unless) to pass a Proc that specifies when the
123 action should be cached. Also, you can use :layout => false to cache without
124 layout so that dynamic information in the layout such as logged in user info
125 or the number of items in the cart can be left uncached. This feature is
126 available as of Rails 2.2.
127
128
129 [More: more examples? Walk-through of Action Caching from request to response?
130 Description of Rake tasks to clear cached files? Show example of
131 subdomain caching? Talk about :cache_path, :if and assing blocks/Procs
132 to expire_action?]
133
134 === Fragment Caching
135
136 Life would be perfect if we could get away with caching the entire contents of
137 a page or action and serving it out to the world. Unfortunately, dynamic web
138 applications usually build pages with a variety of components not all of which
139 have the same caching characteristics. In order to address such a dynamically
140 created page where different parts of the page need to be cached and expired
141 differently Rails provides a mechanism called Fragment Caching.
142
143 Fragment Caching allows a fragment of view logic to be wrapped in a cache
144 block and served out of the cache store when the next request comes in.
145
146 As an example, if you wanted to show all the orders placed on your website
147 in real time and didn't want to cache that part of the page, but did want
148 to cache the part of the page which lists all products available, you
149 could use this piece of code:
150
151 [source, ruby]
152 -----------------------------------------------------
153 <% Order.find_recent.each do |o| %>
154 <%= o.buyer.name %> bought <% o.product.name %>
155 <% end %>
156
157 <% cache do %>
158 All available products:
159 <% Product.find(:all).each do |p| %>
160 <%= link_to p.name, product_url(p) %>
161 <% end %>
162 <% end %>
163 -----------------------------------------------------
164
165 The cache block in our example will bind to the action that called it and is
166 written out to the same place as the Action Cache, which means that if you
167 want to cache multiple fragments per action, you should provide an action_suffix to the cache call:
168
169 [source, ruby]
170 -----------------------------------------------------
171 <% cache(:action => 'recent', :action_suffix => 'all_products') do %>
172 All available products:
173 -----------------------------------------------------
174
175 and you can expire it using the expire_fragment method, like so:
176
177 [source, ruby]
178 -----------------------------------------------------
179 expire_fragment(:controller => 'producst', :action => 'recent', :action_suffix => 'all_products)
180 -----------------------------------------------------
181
182 [More: more examples? description of fragment keys and expiration, etc? pagination?]
183
184 === Sweepers
185
186 Cache sweeping is a mechanism which allows you to get around having a ton of
187 expire_{page,action,fragment} calls in your code by moving all the work
188 required to expire cached content into a ActionController::Caching::Sweeper
189 class that is an Observer and looks for changes to an object via callbacks,
190 and when a change occurs it expires the caches associated with that object n
191 an around or after filter.
192
193 Continuing with our Product controller example, we could rewrite it with a
194 sweeper such as the following:
195
196 [source, ruby]
197 -----------------------------------------------------
198 class StoreSweeper < ActionController::Caching::Sweeper
199 observe Product # This sweeper is going to keep an eye on the Post model
200
201 # If our sweeper detects that a Post was created call this
202 def after_create(product)
203 expire_cache_for(product)
204 end
205
206 # If our sweeper detects that a Post was updated call this
207 def after_update(product)
208 expire_cache_for(product)
209 end
210
211 # If our sweeper detects that a Post was deleted call this
212 def after_destroy(product)
213 expire_cache_for(product)
214 end
215
216 private
217 def expire_cache_for(record)
218 # Expire the list page now that we added a new product
219 expire_page(:controller => '#{record}', :action => 'list')
220
221 # Expire a fragment
222 expire_fragment(:controller => '#{record}', :action => 'recent', :action_suffix => 'all_products')
223 end
224 end
225 -----------------------------------------------------
226
227 Then we add it to our controller to tell it to call the sweeper when certain
228 actions are called. So, if we wanted to expire the cached content for the
229 list and edit actions when the create action was called, we could do the
230 following:
231
232 [source, ruby]
233 -----------------------------------------------------
234 class ProductsController < ActionController
235
236 before_filter :authenticate, :only => [ :edit, :create ]
237 caches_page :list
238 caches_action :edit
239 cache_sweeper :store_sweeper, :only => [ :create ]
240
241 def list; end
242
243 def create
244 expire_page :action => :list
245 expire_action :action => :edit
246 end
247
248 def edit; end
249
250 end
251 -----------------------------------------------------
252
253 [More: more examples? better sweepers?]
254
255 === SQL Caching
256
257 Query caching is a Rails feature that caches the result set returned by each
258 query so that if Rails encounters the same query again for that request, it
259 will used the cached result set as opposed to running the query against the
260 database again.
261
262 For example:
263
264 [source, ruby]
265 -----------------------------------------------------
266 class ProductsController < ActionController
267
268 before_filter :authenticate, :only => [ :edit, :create ]
269 caches_page :list
270 caches_action :edit
271 cache_sweeper :store_sweeper, :only => [ :create ]
272
273 def list
274 # Run a find query
275 Product.find(:all)
276
277 ...
278
279 # Run the same query again
280 Product.find(:all)
281 end
282
283 def create
284 expire_page :action => :list
285 expire_action :action => :edit
286 end
287
288 def edit; end
289
290 end
291 -----------------------------------------------------
292
293 In the 'list' action above, the result set returned by the first
294 Product.find(:all) will be cached and will be used to avoid querying the
295 database again the second time that finder is called.
296
297 Query caches are created at the start of an action and destroyed at the end of
298 that action and thus persist only for the duration of the action.
299
300 === Cache stores
301
302 Rails provides different stores for the cached data for action and fragment
303 caches. Page caches are always stored on disk.
304
305 The cache stores provided include:
306
307 1) Memory store: Cached data is stored in the memory allocated to the Rails
308 process, which is fine for WEBrick and for FCGI (if you
309 don't care that each FCGI process holds its own fragment
310 store). It's not suitable for CGI as the process is thrown
311 away at the end of each request. It can potentially also
312 take up a lot of memory since each process keeps all the
313 caches in memory.
314
315 [source, ruby]
316 -----------------------------------------------------
317 ActionController::Base.cache_store = :memory_store
318 -----------------------------------------------------
319
320 2) File store: Cached data is stored on the disk, this is the default store
321 and the default path for this store is: /tmp/cache. Works
322 well for all types of environments and allows all processes
323 running from the same application directory to access the
324 cached content.
325
326
327 [source, ruby]
328 -----------------------------------------------------
329 ActionController::Base.cache_store = :file_store, "/path/to/cache/directory"
330 -----------------------------------------------------
331
332 3) DRb store: Cached data is stored in a separate shared DRb process that all
333 servers communicate with. This works for all environments and
334 only keeps one cache around for all processes, but requires
335 that you run and manage a separate DRb process.
336
337 [source, ruby]
338 -----------------------------------------------------
339 ActionController::Base.cache_store = :drb_store, "druby://localhost:9192"
340 -----------------------------------------------------
341
342 4) MemCached store: Works like DRbStore, but uses Danga's MemCache instead.
343 Requires the ruby-memcache library:
344 gem install ruby-memcache.
345
346 [source, ruby]
347 -----------------------------------------------------
348 ActionController::Base.cache_store = :mem_cache_store, "localhost"
349 -----------------------------------------------------
350
351 5) Custom store: You can define your own cache store (new in Rails 2.1)
352
353 [source, ruby]
354 -----------------------------------------------------
355 ActionController::Base.cache_store = MyOwnStore.new("parameter")
356 -----------------------------------------------------
357
358 == Advanced Caching
359
360 Along with the built-in mechanisms outlined above, a number of excellent
361 plugins exist to help with finer grained control over caching. These include
362 Chris Wanstrath's excellent cache_fu plugin (more info here:
363 http://errtheblog.com/posts/57-kickin-ass-w-cachefu) and Evan Weaver's
364 interlock plugin (more info here:
365 http://blog.evanweaver.com/articles/2007/12/13/better-rails-caching/). Both
366 of these plugins play nice with memcached and are a must-see for anyone
367 seriously considering optimizing their caching needs.