applied my changes - initial import
[boxroom-stian.git] / vendor / plugins / tiny_mce_gzip / lib / gzip_action_cache.rb
blobf8a5fc6a43f0971bcc759332b4343dfa46358924
1 module ActionController\r
2   module Caching\r
3         module Actions\r
4 #      \r
5       module ClassMethods #:nodoc:\r
6         def caches_gzip_action(*actions)\r
7           around_filter(GzipActionCacheFilter.new(perform_caching, *actions))\r
8         end\r
9       end\r
11       class GzipActionCacheFilter #:nodoc:\r
12         begin \r
13           require 'zlib' \r
14           require 'stringio' \r
15           GZIP_SUPPORTED = true \r
16         rescue \r
17           GZIP_SUPPORTED = false \r
18         end \r
19         \r
20         def initialize(perform_caching, *actions, &block)\r
21           @actions = actions\r
22           @perform_caching = perform_caching\r
23         end\r
25         def before(controller)\r
26           return unless @actions.include?(controller.action_name.intern)\r
28           if @perform_caching\r
29             if cache = controller.read_fragment(controller.url_for.split("://").last)\r
30               controller.rendered_action_cache = true\r
31               \r
32               if accepts_gzip?(controller)\r
33                 cache = compress_output(cache)\r
34                 controller.response.headers['Content-encoding'] = @compression_encoding\r
35               end \r
36               \r
37               controller.send(:render_text, cache)\r
38               return false\r
39             end\r
40           elsif accepts_gzip?(controller)\r
41             controller.response.body = compress_output(controller.response.body)\r
42           end\r
43         end\r
45         def after(controller)\r
46           return if !@perform_caching || !@actions.include?(controller.action_name.intern) || controller.rendered_action_cache\r
47           controller.write_fragment(controller.url_for.split("://").last, controller.response.body)\r
48         end\r
49         \r
50         private\r
51           \r
52           def accepts_gzip?(controller)\r
53             return false unless GZIP_SUPPORTED \r
54             accepts = controller.request.env['HTTP_ACCEPT_ENCODING'] \r
55             return false unless accepts && accepts =~ /(x-gzip|gzip)/ \r
56             @compression_encoding = $1 \r
57             true \r
58           end\r
59           \r
60           def compress_output(body) \r
61             output = StringIO.new \r
62             def output.close \r
63               # Zlib does a close. Bad Zlib... \r
64               rewind \r
65             end \r
66             gz = Zlib::GzipWriter.new(output) \r
67             gz.write(body) \r
68             gz.close \r
69             if output.length < body.length \r
70               @old_response_body = body \r
71               output.string \r
72             end \r
73           end \r
74         \r
75       end\r
76     end\r
77   end\r
78 end\r
79