Caching in Rails
One can perform caching in rails on different levels
- page
- action
- page fragments
- model
- method
All these issues are covered by plugin
cache_fu.
Definitely you should look through presentation available on the plugin's page.
Caching in rails is covered to great extent in
The simple problem
I have to solve the following problem:
Cache pages/actions only for unauthorized users.
Existing solutions
There are some published solutions:
My solution
A great many lines of code are written for implementing caching in rails.
But I would like to add one more small chunk:
# Use this instead of caches_action
def caches_action_unless_auth(*actions)
options = nil
options = actions.pop if actions.last.is_a?(Hash)
@@check_auth_count ||= 0
before_method = "check_auth_methods_#{(@@check_auth_count += 1)}".to_sym
self.class_eval do
define_method(before_method) do
if authenticated?
self.action_name += '_auth'
end
end
actions.each do |action|
define_method(action.to_s + '_auth') do
self.send(action)
render :action=>action unless performed?
end
end
end
before_filter before_method, :only=>actions
actions << options if options
caches_action *actions
before_method
end
Cache is used and created only if
controller method
authenticated? returns true.
Line
self.action_name += '_auth'
is really tricky, but works!
Method
caches_action_unless_auth
could receive options passed to caches_action.
So it can be used along with
cache_fu
and
conditional_caching
plugins.
--
ArtemVoroztsov - 22 Mar 2008