| Module | ConditionalActionCaching |
| In: |
lib/action_caching.rb
|
# File lib/action_caching.rb, line 2
2: def self.included(mod)
3: mod.class_eval do
4: attr_accessor :check
5:
6: # This code allows a block from the caches_action method.
7: # See comments above explaining why it's commented out.
8: #
9: # alias_method :default_initialize, :initialize
10: #
11: # def initialize(*actions, &block)
12: # @block = block
13: # default_initialize(*actions, &block)
14: # end
15:
16: alias_method :default_before, :before
17:
18: # This method, aliased from the default version, will only
19: # attempt to cache if there's an :if parameter supplied
20: # with the caches_action call. The :if value can be either
21: # a Proc or a symbol pointing to an instance method of the
22: # controller.
23: #
24: # === Examples
25: # Using a symbol:
26: #
27: # caches_action :index, :if => :i_can_has_cache?
28: # # ...
29: # def i_can_has_cache?
30: # Time.now.wday == 1 # only cache on Mondays
31: # end
32: #
33: # Using a Proc:
34: #
35: # caches_action :index, :if => Proc.new { Time.now.wday == 1 }
36: def before(controller)
37: if @options.nil? # @options is only set in edge
38: @options = @actions.last.is_a?(Hash) ? @actions.pop : {}
39: end
40:
41: self.check = (@options[:if] || @block)
42:
43: return default_before(controller) if check?(controller)
44: end
45:
46: alias_method :default_after, :after
47:
48: def after(controller) #:nodoc:
49: return default_after(controller) if check?(controller)
50: end
51:
52: private
53:
54: def check?(controller)
55: case check
56: when nil
57: true
58: when Symbol
59: controller.send(check)
60: when Proc
61: controller.instance_eval(&check)
62: else
63: raise ArgumentError.new
64: end
65: end
66: end
67: end
This method, aliased from the default version, will only attempt to cache if there‘s an :if parameter supplied with the caches_action call. The :if value can be either a Proc or a symbol pointing to an instance method of the controller.
Using a symbol:
caches_action :index, :if => :i_can_has_cache?
# ...
def i_can_has_cache?
Time.now.wday == 1 # only cache on Mondays
end
Using a Proc:
caches_action :index, :if => Proc.new { Time.now.wday == 1 }
# File lib/action_caching.rb, line 36
36: def before(controller)
37: if @options.nil? # @options is only set in edge
38: @options = @actions.last.is_a?(Hash) ? @actions.pop : {}
39: end
40:
41: self.check = (@options[:if] || @block)
42:
43: return default_before(controller) if check?(controller)
44: end