markbates / mack-more

All the extra stuff you could want for the Mack Framework.

This URL has Read+Write access

mack-more / mack-caching / lib / page_caching.rb
100644 76 lines (61 sloc) 1.884 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
module Mack
  module Caching
    class PageCaching
      
      def initialize(app)
        @app = app
      end
 
      def call(env)
        if app_config.use_page_caching
          request = Mack::Request.new(env)
          page = Cachetastic::Caches::PageCache.get(request.fullpath)
          if page
            response = Mack::Response.new
            response["Content-Type"] = page.content_type
            response.write(page.body)
            return response.finish
          end
          ret = @app.call(env)
          res = ret[2]
          if res["cache_this_page"] && res.successful?
            Cachetastic::Caches::PageCache.set(request.fullpath, Mack::Caching::PageCaching::Page.new(res.body, res["Content-Type"]))
          end
          return ret
        end
        return @app.call(env)
      end
 
      class Page
        
        attr_reader :body
        attr_reader :content_type
        
        def initialize(body, content_type = "text/html")
          if body.is_a?(Array)
            raise Mack::Caching::PageCaching::UncacheableError.new("Multipart pages can not be cached!") if body.size > 1
            @body = body.first
          else
            @body = body
          end
          @content_type = content_type
        end
        
        def to_s
          @body
        end
        
      end
      
      class UncacheableError < StandardError
        def initialize(message)
          super(message)
        end
      end # UncacheableError
      
    end # PageCaching
  end # Caching
  
  module Controller
    
    module ClassMethods
      def cache_pages(options = {})
        before_filter :set_page_cache_header, options
      end
    end
    
    private
    def set_page_cache_header
      response["cache_this_page"] = "true"
    end
    
  end
  
end # Mack
 
Mack::Utils::Server::Registry.instance.add(Mack::Caching::PageCaching)