@@ -61,10 +61,11 @@ You can modify the default action cache path by passing a
61
61
` :cache_path ` option. This will be passed directly to
62
62
` ActionCachePath.new ` . This is handy for actions with
63
63
multiple possible routes that should be cached differently. If a
64
- block is given, it is called with the current controller instance.
64
+ proc (or an object that responds to ` to_proc ` ) is given, it is
65
+ called with the current controller instance.
65
66
66
- And you can also use ` :if ` (or ` :unless ` ) to pass a
67
- proc that specifies when the action should be cached .
67
+ And you can also use ` :if ` (or ` :unless ` ) to control when the action
68
+ should be cached, similar to how you use them with ` before_action ` .
68
69
69
70
As of Rails 3.0, you can also pass ` :expires_in ` with a time
70
71
interval (in seconds) to schedule expiration of the cached item.
@@ -74,22 +75,32 @@ The following example depicts some of the points made above:
74
75
class ListsController < ApplicationController
75
76
before_action :authenticate, except: :public
76
77
77
- caches_page :public
78
+ # simple fragment cache
79
+ caches_action :current
78
80
79
- caches_action :index, if: Proc.new do
80
- !request.format.json? # cache if is not a JSON request
81
- end
81
+ # expire cache after an hour
82
+ caches_action :archived, expires_in: 1.hour
82
83
83
- caches_action :show, cache_path: { project: 1 },
84
- expires_in: 1.hour
84
+ # cache unless it's a JSON request
85
+ caches_action :index, unless: -> { request.format.json? }
85
86
86
- caches_action :feed, cache_path: Proc.new do
87
- if params[:user_id]
88
- user_list_url(params[:user_id], params[:id])
89
- else
90
- list_url(params[:id])
87
+ # custom cache path
88
+ caches_action :show, cache_path: { project: 1 }
89
+
90
+ # custom cache path with a proc
91
+ caches_action :history, cache_path: -> { request.domain }
92
+
93
+ # custom cache path with a symbol
94
+ caches_action :feed, cache_path: :user_cache_path
95
+
96
+ protected
97
+ def user_cache_path
98
+ if params[:user_id]
99
+ user_list_url(params[:user_id], params[:id])
100
+ else
101
+ list_url(params[:id])
102
+ end
91
103
end
92
- end
93
104
end
94
105
95
106
If you pass ` layout: false ` , it will only cache your action
0 commit comments