response.rb 8.1 KB
Newer Older
1 2
require 'digest/md5'

3
module ActionDispatch # :nodoc:
4 5 6 7 8 9
  # Represents an HTTP response generated by a controller action. One can use
  # an ActionController::Response object to retrieve the current state
  # of the response, or customize the response. An Response object can
  # either represent a "real" HTTP response (i.e. one that is meant to be sent
  # back to the web browser) or a test response (i.e. one that is generated
  # from integration tests). See CgiResponse and TestResponse, respectively.
P
Pratik Naik 已提交
10
  #
11 12 13 14 15
  # Response is mostly a Ruby on Rails framework implement detail, and
  # should never be used directly in controllers. Controllers should use the
  # methods defined in ActionController::Base instead. For example, if you want
  # to set the HTTP response's content MIME type, then use
  # ActionControllerBase#headers instead of Response#headers.
P
Pratik Naik 已提交
16
  #
17 18 19 20 21 22
  # Nevertheless, integration tests may want to inspect controller responses in
  # more detail, and that's when Response can be useful for application
  # developers. Integration test methods such as
  # ActionController::Integration::Session#get and
  # ActionController::Integration::Session#post return objects of type
  # TestResponse (which are of course also of type Response).
P
Pratik Naik 已提交
23 24 25 26 27 28 29 30 31 32
  #
  # For example, the following demo integration "test" prints the body of the
  # controller response to the console:
  #
  #  class DemoControllerTest < ActionController::IntegrationTest
  #    def test_print_root_path_to_console
  #      get('/')
  #      puts @response.body
  #    end
  #  end
33
  class Response < Rack::Response
D
Initial  
David Heinemeier Hansson 已提交
34
    DEFAULT_HEADERS = { "Cache-Control" => "no-cache" }
35
    attr_accessor :request
P
Pratik Naik 已提交
36

37 38 39
    attr_writer :header
    alias_method :headers=, :header=

40 41
    delegate :default_charset, :to => 'ActionController::Base'

D
Initial  
David Heinemeier Hansson 已提交
42
    def initialize
43
      super
44
      @header = Rack::Utils::HeaderHash.new(DEFAULT_HEADERS)
45
    end
46

47 48 49 50 51 52 53 54 55 56 57 58 59
    # The response code of the request
    def response_code
      status.to_s[0,3].to_i rescue 0
    end

    # Returns a String to ensure compatibility with Net::HTTPResponse
    def code
      status.to_s.split(' ')[0]
    end

    def message
      status.to_s.split(' ',2)[1] || StatusCodes::STATUS_CODES[response_code]
    end
60
    alias_method :status_message, :message
61

62 63 64 65 66
    def body
      str = ''
      each { |part| str << part.to_s }
      str
    end
67

68 69
    def body=(body)
      @body =
70
        if body.respond_to?(:to_str)
71 72 73 74 75 76 77 78
          [body]
        else
          body
        end
    end

    def body_parts
      @body
D
Initial  
David Heinemeier Hansson 已提交
79 80
    end

81 82 83 84
    def location
      headers['Location']
    end
    alias_method :redirect_url, :location
85

86 87 88
    def location=(url)
      headers['Location'] = url
    end
89

P
Pratik Naik 已提交
90 91 92 93 94 95 96 97
    # Sets the HTTP response's content MIME type. For example, in the controller
    # you could write this:
    #
    #  response.content_type = "text/plain"
    #
    # If a character set has been defined for this response (see charset=) then
    # the character set information will also be included in the content type
    # information.
98
    def content_type=(mime_type)
99 100 101 102 103 104
      self.headers["Content-Type"] =
        if mime_type =~ /charset/ || (c = charset).nil?
          mime_type.to_s
        else
          "#{mime_type}; charset=#{c}"
        end
105
    end
106

P
Pratik Naik 已提交
107
    # Returns the response's content MIME type, or nil if content type has been set.
108
    def content_type
109
      content_type = String(headers["Content-Type"] || headers["type"]).split(";")[0]
110 111
      content_type.blank? ? nil : content_type
    end
112 113 114 115 116 117 118 119 120 121

    # Set the charset of the Content-Type header. Set to nil to remove it.
    # If no content type is set, it defaults to HTML.
    def charset=(charset)
      headers["Content-Type"] =
        if charset
          "#{content_type || Mime::HTML}; charset=#{charset}"
        else
          content_type || Mime::HTML.to_s
        end
122
    end
123

124
    def charset
125
      charset = String(headers["Content-Type"] || headers["type"]).split(";")[1]
126 127 128
      charset.blank? ? nil : charset.strip.split("=")[1]
    end

129
    def last_modified
130 131 132 133 134 135 136
      if last = headers['Last-Modified']
        Time.httpdate(last)
      end
    end

    def last_modified?
      headers.include?('Last-Modified')
137
    end
138

139 140
    def last_modified=(utc_time)
      headers['Last-Modified'] = utc_time.httpdate
141
    end
142

143 144 145
    def etag
      headers['ETag']
    end
146

147 148 149
    def etag?
      headers.include?('ETag')
    end
150

151
    def etag=(etag)
152 153 154 155 156
      if etag.blank?
        headers.delete('ETag')
      else
        headers['ETag'] = %("#{Digest::MD5.hexdigest(ActiveSupport::Cache.expand_cache_key(etag))}")
      end
D
Initial  
David Heinemeier Hansson 已提交
157
    end
158

159 160 161 162 163 164 165 166 167
    def sending_file?
      headers["Content-Transfer-Encoding"] == "binary"
    end

    def assign_default_content_type_and_charset!
      self.content_type ||= Mime::HTML
      self.charset ||= default_charset unless sending_file?
    end

168
    def prepare!
169
      assign_default_content_type_and_charset!
170
      handle_conditional_get!
171
      set_content_length!
172
      convert_content_type!
173
      convert_language!
174
      convert_cookies!
175
    end
176

177 178 179 180 181
    def each(&callback)
      if @body.respond_to?(:call)
        @writer = lambda { |x| callback.call(x) }
        @body.call(self, self)
      else
182
        @body.each { |part| callback.call(part.to_s) }
183 184 185 186 187 188 189
      end

      @writer = callback
      @block.call(self) if @block
    end

    def write(str)
190 191
      str = str.to_s
      @writer.call str
192 193 194
      str
    end

195
    def set_cookie(key, value)
196
      if value.has_key?(:http_only)
197 198 199
        ActiveSupport::Deprecation.warn(
          "The :http_only option in ActionController::Response#set_cookie " +
          "has been renamed. Please use :httponly instead.", caller)
200
        value[:httponly] ||= value.delete(:http_only)
201
      end
202 203

      super(key, value)
204 205
    end

206 207 208 209 210
    # Returns the response cookies, converted to a Hash of (name => value) pairs
    #
    #   assert_equal 'AuthorOfNewPage', r.cookies['author']
    def cookies
      cookies = {}
211 212 213 214 215 216 217 218
      if header = headers['Set-Cookie']
        header = header.split("\n") if header.respond_to?(:to_str)
        header.each do |cookie|
          if pair = cookie.split(';').first
            key, value = pair.split("=").map { |v| Rack::Utils.unescape(v) }
            cookies[key] = value
          end
        end
219 220 221 222
      end
      cookies
    end

223
    private
224 225 226 227 228 229 230 231
      def handle_conditional_get!
        if etag? || last_modified?
          set_conditional_cache_control!
        elsif nonempty_ok_response?
          self.etag = body

          if request && request.etag_matches?(etag)
            self.status = '304 Not Modified'
232
            self.body = []
233 234 235 236
          end

          set_conditional_cache_control!
        end
237 238
      end

239
      def nonempty_ok_response?
240
        ok = !status || status.to_s[0..2] == '200'
J
Jeremy Kemper 已提交
241 242 243 244 245
        ok && string_body?
      end

      def string_body?
        !body_parts.respond_to?(:call) && body_parts.any? && body_parts.all? { |part| part.is_a?(String) }
246 247 248 249 250 251 252 253
      end

      def set_conditional_cache_control!
        if headers['Cache-Control'] == DEFAULT_HEADERS['Cache-Control']
          headers['Cache-Control'] = 'private, max-age=0, must-revalidate'
        end
      end

254
      def convert_content_type!
255 256
        headers['Content-Type'] ||= "text/html"
        headers['Content-Type'] += "; charset=" + headers.delete('charset') if headers['charset']
257
      end
258

259 260
      # Don't set the Content-Length for block-based bodies as that would mean
      # reading it all into memory. Not nice for, say, a 2GB streaming file.
261
      def set_content_length!
262 263 264 265
        if status && status.to_s[0..2] == '204'
          headers.delete('Content-Length')
        elsif length = headers['Content-Length']
          headers['Content-Length'] = length.to_s
J
Jeremy Kemper 已提交
266
        elsif string_body? && (!status || status.to_s[0..2] != '304')
267
          headers["Content-Length"] = Rack::Utils.bytesize(body).to_s
268
        end
269 270 271 272 273 274
      end

      def convert_language!
        headers["Content-Language"] = headers.delete("language") if headers["language"]
      end

275
      def convert_cookies!
276 277 278 279 280 281 282
        headers['Set-Cookie'] =
          if header = headers['Set-Cookie']
            header = header.split("\n") if header.respond_to?(:to_str)
            header.compact
          else
            []
          end
283
      end
D
Initial  
David Heinemeier Hansson 已提交
284
  end
285
end