actions.rb 7.3 KB
Newer Older
1 2 3 4
require 'set'

module ActionController #:nodoc:
  module Caching
Y
Yehuda Katz 已提交
5 6
    # Action caching is similar to page caching by the fact that the entire
    # output of the response is cached, but unlike page caching, every
7 8 9 10
    # request still goes through Action Pack. The key benefit of this is
    # that filters run before the cache is served, which allows for
    # authentication and other restrictions on whether someone is allowed
    # to execute such action. Example:
11 12 13
    #
    #   class ListsController < ApplicationController
    #     before_filter :authenticate, :except => :public
14
    #
15
    #     caches_page   :public
16
    #     caches_action :index, :show
17 18
    #   end
    #
19 20 21 22
    # In this example, the +public+ action doesn't require authentication
    # so it's possible to use the faster page caching. On the other hand
    # +index+ and +show+ require authentication. They can still be cached,
    # but we need action caching for them.
23
    #
24 25 26
    # Action caching uses fragment caching internally and an around
    # filter to do the job. The fragment cache is named according to
    # the host and path of the request. A page that is accessed at
27 28 29 30
    # <tt>http://david.example.com/lists/show/1</tt> will result in a fragment named
    # <tt>david.example.com/lists/show/1</tt>. This allows the cacher to
    # differentiate between <tt>david.example.com/lists/</tt> and
    # <tt>jamis.example.com/lists/</tt> -- which is a helpful way of assisting
Y
Yehuda Katz 已提交
31
    # the subdomain-as-account-key pattern.
32
    #
Y
Yehuda Katz 已提交
33
    # Different representations of the same resource, e.g.
34 35
    # <tt>http://david.example.com/lists</tt> and
    # <tt>http://david.example.com/lists.xml</tt>
Y
Yehuda Katz 已提交
36 37 38
    # are treated like separate requests and so are cached separately.
    # Keep in mind when expiring an action cache that
    # <tt>:action => 'lists'</tt> is not the same as
39
    # <tt>:action => 'list', :format => :xml</tt>.
40
    #
O
Oge Nnadi 已提交
41
    # You can modify the default action cache path by passing a
42
    # <tt>:cache_path</tt> option. This will be passed directly to
A
Alexey Vakhov 已提交
43
    # <tt>ActionCachePath.new</tt>. This is handy for actions with
44 45 46 47 48
    # multiple possible routes that should be cached differently. If a
    # block is given, it is called with the current controller instance.
    #
    # And you can also use <tt>:if</tt> (or <tt>:unless</tt>) to pass a
    # proc that specifies when the action should be cached.
49
    #
50
    # As of Rails 3.0, you can also pass <tt>:expires_in</tt> with a time
51
    # interval (in seconds) to schedule expiration of the cached item.
52
    #
53
    # The following example depicts some of the points made above:
54
    #
55 56
    #   class ListsController < ApplicationController
    #     before_filter :authenticate, :except => :public
57 58 59
    #
    #     caches_page :public
    #
60
    #     caches_action :index, :if => Proc.new do
61
    #       !request.format.json?  # cache if is not a JSON request
Y
Yehuda Katz 已提交
62 63 64 65 66
    #     end
    #
    #     caches_action :show, :cache_path => { :project => 1 },
    #       :expires_in => 1.hour
    #
67
    #     caches_action :feed, :cache_path => Proc.new do
68 69
    #       if params[:user_id]
    #         user_list_url(params[:user_id, params[:id])
Y
Yehuda Katz 已提交
70
    #       else
71
    #         list_url(params[:id])
Y
Yehuda Katz 已提交
72 73
    #       end
    #     end
74
    #   end
75
    #
76 77 78 79 80 81 82
    # If you pass <tt>:layout => false</tt>, it will only cache your action
    # content. That's useful when your layout has dynamic information.
    #
    # Warning: If the format of the request is determined by the Accept HTTP
    # header the Content-Type of the cached response could be wrong because
    # no information about the MIME type is stored in the cache key. So, if
    # you first ask for MIME type M in the Accept header, a cache entry is
R
R.T. Lechow 已提交
83
    # created, and then perform a second request to the same resource asking
84
    # for a different MIME type, you'd get the content cached for M.
85
    #
86 87
    # The <tt>:format</tt> parameter is taken into account though. The safest
    # way to cache by MIME type is to pass the format in the route.
88
    module Actions
89 90
      extend ActiveSupport::Concern

91 92 93 94 95
      module ClassMethods
        # Declares that +actions+ should be cached.
        # See ActionController::Caching::Actions for details.
        def caches_action(*actions)
          return unless cache_configured?
96
          options = actions.extract_options!
97
          options[:layout] = true unless options.key?(:layout)
98 99
          filter_options = options.extract!(:if, :unless).merge(:only => actions)
          cache_options  = options.extract!(:layout, :cache_path).merge(:store_options => options)
100

101
          around_filter ActionCacheFilter.new(cache_options), filter_options
102 103 104
        end
      end

105
      def _save_fragment(name, options)
106 107 108 109
        content = ""
        response_body.each do |parts|
          content << parts
        end
110

111 112 113 114 115
        if caching_allowed?
          write_fragment(name, content, options)
        else
          content
        end
116 117
      end

Y
Yehuda Katz 已提交
118 119 120
    protected
      def expire_action(options = {})
        return unless cache_configured?
121

122 123
        if options.is_a?(Hash) && options[:action].is_a?(Array)
          options[:action].each {|action| expire_action(options.merge(:action => action)) }
Y
Yehuda Katz 已提交
124 125
        else
          expire_fragment(ActionCachePath.new(self, options, false).path)
126
        end
Y
Yehuda Katz 已提交
127
      end
128 129

      class ActionCacheFilter #:nodoc:
130
        def initialize(options, &block)
131
          @cache_path, @store_options, @cache_layout =
132
            options.values_at(:cache_path, :store_options, :layout)
133 134
        end

135
        def around(controller)
136 137
          cache_layout = @cache_layout.respond_to?(:call) ? @cache_layout.call(controller) : @cache_layout

Y
Yehuda Katz 已提交
138 139 140 141 142 143
          path_options = if @cache_path.respond_to?(:call)
            controller.instance_exec(controller, &@cache_path)
          else
            @cache_path
          end

144
          cache_path = ActionCachePath.new(controller, path_options || {})
145

146 147 148
          body = controller.read_fragment(cache_path.path, @store_options)

          unless body
149
            controller.action_has_layout = false unless cache_layout
150
            yield
151 152
            controller.action_has_layout = true
            body = controller._save_fragment(cache_path.path, @store_options)
153
          end
154

155
          body = controller.render_to_string(:text => body, :layout => true) unless cache_layout
156 157 158

          controller.response_body = body
          controller.content_type = Mime[cache_path.extension || :html]
159 160
        end
      end
161

162 163
      class ActionCachePath
        attr_reader :path, :extension
164

165
        # If +infer_extension+ is true, the cache path extension is looked up from the request's
166
        # path and format. This is desirable when reading and writing the cache, but not when
167 168
        # expiring the cache - expire_action should expire the same files regardless of the
        # request format.
169 170
        def initialize(controller, options = {}, infer_extension = true)
          if infer_extension
Y
Yehuda Katz 已提交
171 172
            @extension = controller.params[:format]
            options.reverse_merge!(:format => @extension) if options.is_a?(Hash)
173
          end
174

175
          path = controller.url_for(options).split('://', 2).last
Y
Yehuda Katz 已提交
176
          @path = normalize!(path)
177
        end
178

179 180
      private
        def normalize!(path)
181
          ext = URI.parser.escape(extension) if extension
182
          path << 'index' if path[-1] == ?/
183
          path << ".#{ext}" if extension and !path.split('?', 2).first.ends_with?(".#{ext}")
184
          URI.parser.unescape(path)
185
        end
186 187 188
      end
    end
  end
189
end