Upgraded Rails and RSpec
[monkeycharger.git] / vendor / rails / actionpack / lib / action_controller / response.rb
blob1d9f6676ba49d5b992c153fa6267dbb57886200d
1 require 'digest/md5'
3 module ActionController
4   class AbstractResponse #:nodoc:
5     DEFAULT_HEADERS = { "Cache-Control" => "no-cache" }
6     attr_accessor :request
7     attr_accessor :body, :headers, :session, :cookies, :assigns, :template, :redirected_to, :redirected_to_method_params, :layout
9     def initialize
10       @body, @headers, @session, @assigns = "", DEFAULT_HEADERS.merge("cookie" => []), [], []
11     end
13     def content_type=(mime_type)
14       self.headers["Content-Type"] = charset ? "#{mime_type}; charset=#{charset}" : mime_type
15     end
16     
17     def content_type
18       content_type = String(headers["Content-Type"] || headers["type"]).split(";")[0]
19       content_type.blank? ? nil : content_type
20     end
21     
22     def charset=(encoding)
23       self.headers["Content-Type"] = "#{content_type || Mime::HTML}; charset=#{encoding}"
24     end
25     
26     def charset
27       charset = String(headers["Content-Type"] || headers["type"]).split(";")[1]
28       charset.blank? ? nil : charset.strip.split("=")[1]
29     end
31     def redirect(to_url, response_status)
32       self.headers["Status"] = response_status
33       self.headers["Location"] = to_url
35       self.body = "<html><body>You are being <a href=\"#{to_url}\">redirected</a>.</body></html>"
36     end
38     def prepare!
39       handle_conditional_get!
40       convert_content_type!
41       set_content_length!
42     end
45     private
46       def handle_conditional_get!
47         if body.is_a?(String) && (headers['Status'] ? headers['Status'][0..2] == '200' : true)  && !body.empty?
48           self.headers['ETag'] ||= %("#{Digest::MD5.hexdigest(body)}")
49           self.headers['Cache-Control'] = 'private, max-age=0, must-revalidate' if headers['Cache-Control'] == DEFAULT_HEADERS['Cache-Control']
51           if request.headers['HTTP_IF_NONE_MATCH'] == headers['ETag']
52             self.headers['Status'] = '304 Not Modified'
53             self.body = ''
54           end
55         end
56       end
58       def convert_content_type!
59         if content_type = headers.delete("Content-Type")
60           self.headers["type"] = content_type
61         end
62         if content_type = headers.delete("Content-type")
63           self.headers["type"] = content_type
64         end
65         if content_type = headers.delete("content-type")
66           self.headers["type"] = content_type
67         end
68       end
69     
70       # Don't set the Content-Length for block-based bodies as that would mean reading it all into memory. Not nice
71       # for, say, a 2GB streaming file.
72       def set_content_length!
73         self.headers["Content-Length"] = body.size unless body.respond_to?(:call)
74       end
75   end
76 end