This repository was archived by the owner on Jan 7, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcaching_with_rails.html
More file actions
555 lines (490 loc) · 31.2 KB
/
caching_with_rails.html
File metadata and controls
555 lines (490 loc) · 31.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Ruby on Rails Guides: Caching with Rails: An overview</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />
</head>
<body class="guide">
<div id="topNav">
<div class="wrapper">
<strong>More at <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
<a href="http://rubyonrails.org/">Overview</a> |
<a href="http://rubyonrails.org/download">Download</a> |
<a href="http://rubyonrails.org/deploy">Deploy</a> |
<a href="http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/overview">Code</a> |
<a href="http://rubyonrails.org/screencasts">Screencasts</a> |
<a href="http://rubyonrails.org/documentation">Documentation</a> |
<a href="http://rubyonrails.org/ecosystem">Ecosystem</a> |
<a href="http://rubyonrails.org/community">Community</a> |
<a href="http://weblog.rubyonrails.org/">Blog</a>
</div>
</div>
<div id="header">
<div class="wrapper clearfix">
<h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
<p class="hide"><a href="#mainCol">Skip navigation</a>.</p>
<ul class="nav">
<li><a href="index.html">홈</a></li>
<li class="index"><a href="index.html" onclick="guideMenu(); return false;" id="guidesMenu">목차</a>
<div id="guides" class="clearfix" style="display: none;">
<hr />
<dl class="L">
<dt>시작</dt>
<dd><a href="getting_started.html">레일즈 시작하기</a></dd>
<dt>모델(Models)</dt>
<dd><a href="migrations.html">레일즈 데이터베이스 마이그레이션</a></dd>
<dd><a href="active_record_validations_callbacks.html">액티브 레코드 데이터 검증(Validation)과 Callback(콜백)</a></dd>
<dd><a href="association_basics.html">액티브 레코드 Association(관계)</a></dd>
<dd><a href="active_record_querying.html">액티브 레코드 쿼리 인터페이스</a></dd>
<dt>뷰(Views)</dt>
<dd><a href="layouts_and_rendering.html">레이아웃(Layouts)과 렌더링(Rendering)</a></dd>
<dd><a href="form_helpers.html">액션 뷰 폼 핼퍼(Action View Form Helpers)</a></dd>
<dt>컨트롤러(Controllers)</dt>
<dd><a href="action_controller_overview.html">액션 컨트롤러 둘러보기</a></dd>
<dd><a href="routing.html">외부 요청에 대한 레일즈 라우팅</a></dd>
</dl>
<dl class="R">
<dt>심화내용</dt>
<dd><a href="active_support_core_extensions.html">액티브 서포트(Active Support) 확장(Core Extensions)</a></dd>
<dd><a href="i18n.html">레일즈 국제화I(nternationalization) API</a></dd>
<dd><a href="action_mailer_basics.html">액션 메일러의 기본</a></dd>
<dd><a href="testing.html">레일즈 어플리케이션 테스트하기</a></dd>
<dd><a href="security.html">레일즈 어플리케이션의 보안</a></dd>
<dd><a href="debugging_rails_applications.html">레일즈 어플리케이션 디버깅</a></dd>
<dd><a href="performance_testing.html">레일즈 어플리케이션 성능 테스트하기</a></dd>
<dd><a href="configuring.html">레일즈 어플리케이션 설정</a></dd>
<dd><a href="command_line.html">레일즈 커멘드라인 도구와 Rake 테스크</a></dd>
<dd><a href="caching_with_rails.html">레일즈를 이용한 캐싱</a></dd>
<dt>레일즈 확장하기(Extending Rails)</dt>
<dd><a href="plugins.html">레일즈 플러그인 작성의 기본</a></dd>
<dd><a href="rails_on_rack.html">렉 위의 레일즈(Rails on Rack)</a></dd>
<dd><a href="generators.html">레일즈 제너레이터(Generator) 제작과 수정</a></dd>
<dt>루비 온 레이즈에 기여하기</dt>
<dd><a href="contributing_to_ruby_on_rails.html">루비 온 레이즈에 기여하기</a></dd>
<dd><a href="api_documentation_guidelines.html">API 문서 가이드라인</a></dd>
<dd><a href="ruby_on_rails_guides_guidelines.html">루비 온 레일즈 가이드에 대한 가이드라인</a></dd>
<dt>Release Notes</dt>
<dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</a></dd>
<dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</a></dd>
<dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</a></dd>
</dl>
</div>
</li>
<li><a href="contribute.html">기여하기</a></li>
<li><a href="credits.html">수고하신 분들</a></li>
</ul>
</div>
</div>
<hr class="hide" />
<div id="feature">
<div class="wrapper">
<h2>Caching with Rails: An overview</h2>
<p>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.</p>
<p>After reading this guide, you should be able to use and configure:</p>
<ul>
<li>Page, action, and fragment caching</li>
<li>Sweepers</li>
<li>Alternative cache stores</li>
<li>Conditional <span class="caps">GET</span> support</li>
</ul>
<div id="subCol">
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
<ol class="chapters">
<li><a href="#basic-caching">Basic Caching</a><ul><li><a href="#page-caching">Page Caching</a></li> <li><a href="#action-caching">Action Caching</a></li> <li><a href="#fragment-caching">Fragment Caching</a></li> <li><a href="#sweepers">Sweepers</a></li> <li><a href="#sql-caching"><span class="caps">SQL</span> Caching</a></li></ul></li><li><a href="#cache-stores">Cache Stores</a></li><li><a href="#conditional-get-support">Conditional <span class="caps">GET</span> support</a></li><li><a href="#further-reading">Further reading</a></li><li><a href="#changelog">Changelog</a></li></ol></div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<h3 id="basic-caching">1 Basic Caching</h3>
<p>This is an introduction to the three types of caching techniques that Rails provides by default without the use of any third party plugins.</p>
<p>To start playing with testing you’ll want to ensure that <tt>config.action_controller.perform_caching</tt> is set to <tt>true</tt> if you’re running in development mode. This flag is normally set in the corresponding <tt>config/environments/*.rb</tt> and caching is disabled by default for development and test, and enabled for production.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.action_controller.perform_caching = true
</pre>
</div>
</notextile>
<h4 id="page-caching">1.1 Page Caching</h4>
<p>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.</p>
<p>So, how do you enable this super-fast cache behavior? Simple, let’s say you have a controller called <tt>ProductsController</tt> and an <tt>index</tt> action that lists all the products</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ProductsController < ActionController
caches_page :index
def index
@products = Products.all
end
end
</pre>
</div>
</notextile>
<p>The first time anyone requests <tt>/products</tt>, Rails will generate a file called <tt>products.html</tt> and the webserver will then look for that file before it passes the next request for <tt>/products</tt> to your Rails application.</p>
<p>By default, the page cache directory is set to <tt>Rails.public_path</tt> (which is usually set to the <tt>public</tt> folder) and this can be configured by changing the configuration setting <tt>config.action_controller.page_cache_directory</tt>. Changing the default from <tt>public</tt> helps avoid naming conflicts, since you may want to put other static html in <tt>public</tt>, but changing this will require web server reconfiguration to let the web server know where to serve the cached files from.</p>
<p>The Page Caching mechanism will automatically add a <tt>.html</tt> extension to requests for pages that do not have an extension to make it easy for the webserver to find those pages and this can be configured by changing the configuration setting <tt>config.action_controller.page_cache_extension</tt>.</p>
<p>In order to expire this page when a new product is added we could extend our example controller like this:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ProductsController < ActionController
caches_page :index
def index
@products = Products.all
end
def create
expire_page :action => :index
end
end
</pre>
</div>
</notextile>
<p>If you want a more complicated expiration scheme, you can use cache sweepers to expire cached objects when things change. This is covered in the section on Sweepers.</p>
<p>Note: Page caching ignores all parameters. For example <tt>/products?page=1</tt> will be written out to the filesystem as <tt>products.html</tt> with no reference to the <tt>page</tt> parameter. Thus, if someone requests <tt>/products?page=2</tt> later, they will get the cached first page. Be careful when page caching <span class="caps">GET</span> parameters in the <span class="caps">URL</span>!</p>
<div class='info'><p>Page caching runs in an after filter. Thus, invalid requests won’t generate spurious cache entries as long as you halt them. Typically, a redirection in some before filter that checks request preconditions does the job.</p></div>
<h4 id="action-caching">1.2 Action Caching</h4>
<p>One of the issues with Page Caching is that you cannot use it for pages that require to restrict access somehow. This is where Action Caching comes in. Action Caching works like Page Caching except for the fact that the incoming web request does go from the webserver to the Rails stack and Action Pack so that before filters can be run on it before the cache is served. This allows authentication and other restriction to be run while still serving the result of the output from a cached copy.</p>
<p>Clearing the cache works in the exact same way as with Page Caching.</p>
<p>Let’s say you only wanted authenticated users to call actions on <tt>ProductsController</tt>.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ProductsController < ActionController
before_filter :authenticate
caches_action :index
def index
@products = Product.all
end
def create
expire_action :action => :index
end
end
</pre>
</div>
</notextile>
<p>You can also use <tt>:if</tt> (or <tt>:unless</tt>) to pass a Proc that specifies when the action should be cached. Also, you can use <tt>:layout => false</tt> to cache without layout so that dynamic information in the layout such as logged in user info or the number of items in the cart can be left uncached. This feature is available as of Rails 2.2.</p>
<p>You can modify the default action cache path by passing a <tt>:cache_path</tt> option. This will be passed directly to <tt>ActionCachePath.path_for</tt>. This is handy for actions with multiple possible routes that should be cached differently. If a block is given, it is called with the current controller instance.</p>
<p>Finally, if you are using memcached, you can also pass <tt>:expires_in</tt>. In fact, all parameters not used by <tt>caches_action</tt> are sent to the underlying cache store.</p>
<div class='info'><p>Action caching runs in an after filter. Thus, invalid requests won’t generate spurious cache entries as long as you halt them. Typically, a redirection in some before filter that checks request preconditions does the job.</p></div>
<h4 id="fragment-caching">1.3 Fragment Caching</h4>
<p>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.</p>
<p>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.</p>
<p>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:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
<% Order.find_recent.each do |o| %>
<%= o.buyer.name %> bought <% o.product.name %>
<% end %>
<% cache do %>
All available products:
<% Product.all.each do |p| %>
<%= link_to p.name, product_url(p) %>
<% end %>
<% end %>
</pre>
</div>
</notextile>
<p>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 <tt>action_suffix</tt> to the cache call:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
<% cache(:action => 'recent', :action_suffix => 'all_products') do %>
All available products:
</pre>
</div>
</notextile>
<p>and you can expire it using the <tt>expire_fragment</tt> method, like so:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
expire_fragment(:controller => 'products', :action => 'recent', :action_suffix => 'all_products')
</pre>
</div>
</notextile>
<p>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 <tt>cache</tt> method with a key, like so:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
<% cache('all_available_products') do %>
All available products:
<% end %>
</pre>
</div>
</notextile>
<p>This fragment is then available to all actions in the <tt>ProductsController</tt> using the key and can be expired the same way:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
expire_fragment('all_available_products')
</pre>
</div>
</notextile>
<h4 id="sweepers">1.4 Sweepers</h4>
<p>Cache sweeping is a mechanism which allows you to get around having a ton of <tt>expire_{page,action,fragment}</tt> calls in your code. It does this by moving all the work required to expire cached content into an <tt>ActionController::Caching::Sweeper</tt> subclass. This class is an observer and looks for changes to an object via callbacks, and when a change occurs it expires the caches associated with that object in an around or after filter.</p>
<p>Continuing with our Product controller example, we could rewrite it with a sweeper like this:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ProductSweeper < ActionController::Caching::Sweeper
observe Product # This sweeper is going to keep an eye on the Product model
# If our sweeper detects that a Product was created call this
def after_create(product)
expire_cache_for(product)
end
# If our sweeper detects that a Product was updated call this
def after_update(product)
expire_cache_for(product)
end
# If our sweeper detects that a Product was deleted call this
def after_destroy(product)
expire_cache_for(product)
end
private
def expire_cache_for(product)
# Expire the index page now that we added a new product
expire_page(:controller => 'products', :action => 'index')
# Expire a fragment
expire_fragment('all_available_products')
end
end
</pre>
</div>
</notextile>
<p>You may notice that the actual product gets passed to the sweeper, so if we were caching the edit action for each product, we could add an expire method which specifies the page we want to expire:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
expire_action(:controller => 'products', :action => 'edit', :id => product)
</pre>
</div>
</notextile>
<p>Then we add it to our controller to tell it to call the sweeper when certain actions are called. So, if we wanted to expire the cached content for the list and edit actions when the create action was called, we could do the following:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ProductsController < ActionController
before_filter :authenticate
caches_action :index
cache_sweeper :product_sweeper
def index
@products = Product.all
end
end
</pre>
</div>
</notextile>
<h4 id="sql-caching">1.5 <span class="caps">SQL</span> Caching</h4>
<p>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.</p>
<p>For example:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ProductsController < ActionController
def index
# Run a find query
@products = Product.all
...
# Run the same query again
@products = Product.all
end
end
</pre>
</div>
</notextile>
<p>The second time the same query is run against the database, it’s not actually going to hit the database. The first time the result is returned from the query it is stored in the query cache (in memory) and the second time it’s pulled from memory.</p>
<p>However, it’s important to note that query caches are created at the start of an action and destroyed at the end of that action and thus persist only for the duration of the action. If you’d like to store query results in a more persistent fashion, you can in Rails by using low level caching.</p>
<h3 id="cache-stores">2 Cache Stores</h3>
<p>Rails provides different stores for the cached data created by action and fragment caches. Page caches are always stored on disk.</p>
<p>Rails 2.1 and above provide <tt>ActiveSupport::Cache::Store</tt> which can be used to cache strings. Some cache store implementations, like <tt>MemoryStore</tt>, are able to cache arbitrary Ruby objects, but don’t count on every cache store to be able to do that.</p>
<p>The default cache stores provided with Rails include:</p>
<p>1) <tt>ActiveSupport::Cache::MemoryStore</tt>: A cache store implementation which stores everything into memory in the same process. If you’re running multiple Ruby on Rails server processes (which is the case if you’re using mongrel_cluster or Phusion Passenger), then this means that your Rails server process instances won’t be able to share cache data with each other. If your application never performs manual cache item expiry (e.g. when you‘re using generational cache keys), then using <tt>MemoryStore</tt> is ok. Otherwise, consider carefully whether you should be using this cache store.</p>
<p><tt>MemoryStore</tt> is not only able to store strings, but also arbitrary Ruby objects.</p>
<p><tt>MemoryStore</tt> is not thread-safe. Use <tt>SynchronizedMemoryStore</tt> instead if you need thread-safety.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
ActionController::Base.cache_store = :memory_store
</pre>
</div>
</notextile>
<p>2) <tt>ActiveSupport::Cache::FileStore</tt>: Cached data is stored on the disk, this is the default store and the default path for this store is <tt>tmp/cache</tt>. Works well for all types of environments and allows all processes running from the same application directory to access the cached content. If <tt>tmp/cache</tt> does not exist, the default store becomes <tt>MemoryStore</tt>.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
ActionController::Base.cache_store = :file_store, "/path/to/cache/directory"
</pre>
</div>
</notextile>
<p>3) <tt>ActiveSupport::Cache::DRbStore</tt>: Cached data is stored in a separate shared DRb process that all servers communicate with. This works for all environments and only keeps one cache around for all processes, but requires that you run and manage a separate DRb process.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
ActionController::Base.cache_store = :drb_store, "druby://localhost:9192"
</pre>
</div>
</notextile>
<p>4) <tt>ActiveSupport::Cache::MemCacheStore</tt>: Works like <tt>DRbStore</tt>, but uses Danga’s <tt>memcached</tt> instead. Rails uses the bundled <tt>memcached-client</tt> gem by default. This is currently the most popular cache store for production websites.</p>
<p>Special features:</p>
<ul>
<li>Clustering and load balancing. One can specify multiple memcached servers, and <tt>MemCacheStore</tt> will load balance between all available servers. If a server goes down, then <tt>MemCacheStore</tt> will ignore it until it goes back online.</li>
<li>Time-based expiry support. See <tt>write</tt> and the <tt>:expires_in</tt> option.</li>
<li>Per-request in memory cache for all communication with the <tt>memcached</tt> server(s).</li>
</ul>
<p>It also accepts a hash of additional options:</p>
<ul>
<li><tt>:namespace</tt>: specifies a string that will automatically be prepended to keys when accessing the memcached store.</li>
<li><tt>:readonly</tt>: a boolean value that when set to true will make the store read-only, with an error raised on any attempt to write.</li>
<li><tt>:multithread</tt>: a boolean value that adds thread safety to read/write operations – it is unlikely you’ll need to use this option as the Rails threadsafe! method offers the same functionality.</li>
</ul>
<p>The read and write methods of the <tt>MemCacheStore</tt> accept an options hash too. When reading you can specify <tt>:raw => true</tt> to prevent the object being marshaled (by default this is false which means the raw value in the cache is passed to <tt>Marshal.load</tt> before being returned to you.)</p>
<p>When writing to the cache it is also possible to specify <tt>:raw => true</tt> means the value is not passed to <tt>Marshal.dump</tt> before being stored in the cache (by default this is false).</p>
<p>The write method also accepts an <tt>:unless_exist</tt> flag which determines whether the memcached add (when true) or set (when false) method is used to store the item in the cache and an <tt>:expires_in</tt> option that specifies the time-to-live for the cached item in seconds.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
ActionController::Base.cache_store = :mem_cache_store, "localhost"
</pre>
</div>
</notextile>
<p>5) <tt>ActiveSupport::Cache::SynchronizedMemoryStore</tt>: Like <tt>MemoryStore</tt> but thread-safe.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
ActionController::Base.cache_store = :synchronized_memory_store
</pre>
</div>
</notextile>
<p>6) <tt>ActiveSupport::Cache::CompressedMemCacheStore</tt>: Works just like the regular <tt>MemCacheStore</tt> but uses GZip to decompress/compress on read/write.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
ActionController::Base.cache_store = :compressed_mem_cache_store, "localhost"
</pre>
</div>
</notextile>
<p>7) Custom store: You can define your own cache store (new in Rails 2.1).</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
ActionController::Base.cache_store = MyOwnStore.new("parameter")
</pre>
</div>
</notextile>
<div class='note'><p><tt>config.cache_store</tt> can be used in place of <tt>ActionController::Base.cache_store</tt> in your <tt>Rails::Initializer.run</tt> block in <tt>environment.rb</tt></p></div>
<p>In addition to all of this, Rails also adds the <tt>ActiveRecord::Base#cache_key</tt> method that generates a key using the class name, <tt>id</tt> and <tt>updated_at</tt> timestamp (if available).</p>
<p>You can access these cache stores at a low level for storing queries and other objects. Here’s an example:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Rails.cache.read("city") # => nil
Rails.cache.write("city", "Duckburgh")
Rails.cache.read("city") # => "Duckburgh"
</pre>
</div>
</notextile>
<h3 id="conditional-get-support">3 Conditional <span class="caps">GET</span> support</h3>
<p>Conditional GETs are a feature of the <span class="caps">HTTP</span> specification that provide a way for web servers to tell browsers that the response to a <span class="caps">GET</span> request hasn’t changed since the last request and can be safely pulled from the browser cache.</p>
<p>They work by using the <tt>HTTP_IF_NONE_MATCH</tt> and <tt>HTTP_IF_MODIFIED_SINCE</tt> 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.</p>
<p>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:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ProductsController < ApplicationController
def show
@product = Product.find(params[:id])
# If the request is stale according to the given timestamp and etag value
# (i.e. it needs to be processed again) then execute this block
if stale?(:last_modified => @product.updated_at.utc, :etag => @product)
respond_to do |wants|
# ... normal response processing
end
end
# If the request is fresh (i.e. it's not modified) then you don't need to do
# anything. The default render checks for this using the parameters
# used in the previous call to stale? and will automatically send a
# :not_modified. So that's it, you're done.
end
</pre>
</div>
</notextile>
<p>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:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ProductsController < ApplicationController
# This will automatically send back a :not_modified if the request is fresh,
# and will render the default template (product.*) if it's stale.
def show
@product = Product.find(params[:id])
fresh_when :last_modified => @product.published_at.utc, :etag => @product
end
end
</pre>
</div>
</notextile>
<h3 id="further-reading">4 Further reading</h3>
<ul>
<li><a href="http://railslab.newrelic.com/scaling-rails">Scaling Rails Screencasts</a></li>
</ul>
<h3 id="changelog">5 Changelog</h3>
<ul>
<li>May 02, 2009: Formatting cleanups</li>
<li>April 26, 2009: Clean up typos in submitted patch</li>
<li>April 1, 2009: Made a bunch of small fixes</li>
<li>February 22, 2009: Beefed up the section on cache_stores</li>
<li>December 27, 2008: Typo fixes</li>
<li>November 23, 2008: Incremental updates with various suggested changes and formatting cleanup</li>
<li>September 15, 2008: Initial version by Aditya Chadha</li>
</ul>
<h3>Feedback</h3>
<p>
You're encouraged to help in keeping the quality of this guide.
</p>
<p>
If you see any typos or factual errors you are confident to
patch, please clone <a href="https://github.com/lifo/docrails">docrails</a>
and push the change yourself. That branch of Rails has public write access.
Commits are still reviewed, but that happens after you've submitted your
contribution. <a href="https://github.com/lifo/docrails">docrails</a> is
cross-merged with master periodically.
</p>
<p>
You may also find incomplete content, or stuff that is not up to date.
Please do add any missing documentation for master. Check the
<a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a>
for style and conventions.
</p>
<p>
Issues may also be reported in <a href="https://github.com/lifo/docrails/issues">Github</a>.
</p>
<p>And last but not least, any kind of discussion regarding Ruby on Rails
documentation is very welcome in the <a href="http://groups.google.com/group/rubyonrails-docs">rubyonrails-docs mailing list</a>.
</p>
</div>
</div>
</div>
<hr class="hide" />
<div id="footer">
<div class="wrapper">
<p>This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike 3.0</a> License</p>
<p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p>
</div>
</div>
<script type="text/javascript" src="javascripts/guides.js"></script>
<script type="text/javascript" src="javascripts/syntaxhighlighter/shCore.js"></script>
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushRuby.js"></script>
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushXml.js"></script>
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushSql.js"></script>
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushPlain.js"></script>
<script type="text/javascript">
SyntaxHighlighter.all()
</script>
</body>
</html>