559c38efd0c521d2f8877cfc840cc658f1b7aa4f
[depot.git] / response.rb
1 require 'digest/md5'
2
3 module ActionController # :nodoc:
4 # Represents an HTTP response generated by a controller action. One can use an
5 # ActionController::AbstractResponse object to retrieve the current state of the
6 # response, or customize the response. An AbstractResponse object can either
7 # represent a "real" HTTP response (i.e. one that is meant to be sent back to the
8 # web browser) or a test response (i.e. one that is generated from integration
9 # tests). See CgiResponse and TestResponse, respectively.
10 #
11 # AbstractResponse is mostly a Ruby on Rails framework implement detail, and should
12 # never be used directly in controllers. Controllers should use the methods defined
13 # in ActionController::Base instead. For example, if you want to set the HTTP
14 # response's content MIME type, then use ActionControllerBase#headers instead of
15 # AbstractResponse#headers.
16 #
17 # Nevertheless, integration tests may want to inspect controller responses in more
18 # detail, and that's when AbstractResponse can be useful for application developers.
19 # Integration test methods such as ActionController::Integration::Session#get and
20 # ActionController::Integration::Session#post return objects of type TestResponse
21 # (which are of course also of type AbstractResponse).
22 #
23 # For example, the following demo integration "test" prints the body of the
24 # controller response to the console:
25 #
26 # class DemoControllerTest < ActionController::IntegrationTest
27 # def test_print_root_path_to_console
28 # get('/')
29 # puts @response.body
30 # end
31 # end
32 class AbstractResponse
33 DEFAULT_HEADERS = { "Cache-Control" => "no-cache" }
34 attr_accessor :request
35
36 # The body content (e.g. HTML) of the response, as a String.
37 attr_accessor :body
38 # The headers of the response, as a Hash. It maps header names to header values.
39 attr_accessor :headers
40 attr_accessor :session, :cookies, :assigns, :template, :layout
41 attr_accessor :redirected_to, :redirected_to_method_params
42
43 delegate :default_charset, :to => 'ActionController::Base'
44
45 def initialize
46 @body, @headers, @session, @assigns = "", DEFAULT_HEADERS.merge("cookie" => []), [], []
47 end
48
49 def status; headers['Status'] end
50 def status=(status) headers['Status'] = status end
51
52 def location; headers['Location'] end
53 def location=(url) headers['Location'] = url end
54
55
56 # Sets the HTTP response's content MIME type. For example, in the controller
57 # you could write this:
58 #
59 # response.content_type = "text/plain"
60 #
61 # If a character set has been defined for this response (see charset=) then
62 # the character set information will also be included in the content type
63 # information.
64 def content_type=(mime_type)
65 self.headers["Content-Type"] =
66 if mime_type =~ /charset/ || (c = charset).nil?
67 mime_type.to_s
68 else
69 "#{mime_type}; charset=#{c}"
70 end
71 end
72
73 # Returns the response's content MIME type, or nil if content type has been set.
74 def content_type
75 content_type = String(headers["Content-Type"] || headers["type"]).split(";")[0]
76 content_type.blank? ? nil : content_type
77 end
78
79 # Set the charset of the Content-Type header. Set to nil to remove it.
80 # If no content type is set, it defaults to HTML.
81 def charset=(charset)
82 headers["Content-Type"] =
83 if charset
84 "#{content_type || Mime::HTML}; charset=#{charset}"
85 else
86 content_type || Mime::HTML.to_s
87 end
88 end
89
90 def charset
91 charset = String(headers["Content-Type"] || headers["type"]).split(";")[1]
92 charset.blank? ? nil : charset.strip.split("=")[1]
93 end
94
95 def last_modified
96 if last = headers['Last-Modified']
97 Time.httpdate(last)
98 end
99 end
100
101 def last_modified?
102 headers.include?('Last-Modified')
103 end
104
105 def last_modified=(utc_time)
106 headers['Last-Modified'] = utc_time.httpdate
107 end
108
109 def etag
110 headers['ETag']
111 end
112
113 def etag?
114 headers.include?('ETag')
115 end
116
117 def etag=(etag)
118 headers['ETag'] = %("#{Digest::MD5.hexdigest(ActiveSupport::Cache.expand_cache_key(etag))}")
119 end
120
121 def redirect(url, status)
122 self.status = status
123 self.location = url.gsub(/[\r\n]/, '')
124 self.body = "<html><body>You are being <a href=\"#{CGI.escapeHTML(url)}\">redirected</a>.</body></html>"
125 end
126
127 def sending_file?
128 headers["Content-Transfer-Encoding"] == "binary"
129 end
130
131 def assign_default_content_type_and_charset!
132 self.content_type ||= Mime::HTML
133 self.charset ||= default_charset unless sending_file?
134 end
135
136 def prepare!
137 assign_default_content_type_and_charset!
138 handle_conditional_get!
139 set_content_length!
140 convert_content_type!
141 end
142
143 private
144 def handle_conditional_get!
145 if etag? || last_modified?
146 set_conditional_cache_control!
147 elsif nonempty_ok_response?
148 self.etag = body
149
150 if request && request.etag_matches?(etag)
151 self.status = '304 Not Modified'
152 self.body = ''
153 end
154
155 set_conditional_cache_control!
156 end
157 end
158
159 def nonempty_ok_response?
160 ok = !status || status[0..2] == '200'
161 ok && body.is_a?(String) && !body.empty?
162 end
163
164 def set_conditional_cache_control!
165 if headers['Cache-Control'] == DEFAULT_HEADERS['Cache-Control']
166 headers['Cache-Control'] = 'private, max-age=0, must-revalidate'
167 end
168 end
169
170 def convert_content_type!
171 if content_type = headers.delete("Content-Type")
172 self.headers["type"] = content_type
173 end
174 if content_type = headers.delete("Content-type")
175 self.headers["type"] = content_type
176 end
177 if content_type = headers.delete("content-type")
178 self.headers["type"] = content_type
179 end
180 end
181
182 # Don't set the Content-Length for block-based bodies as that would mean reading it all into memory. Not nice
183 # for, say, a 2GB streaming file.
184 def set_content_length!
185 unless body.respond_to?(:call) || (status && status[0..2] == '304')
186 self.headers["Content-Length"] ||= body.size
187 end
188 end
189 end
190 end