response.rb 6.9 KB
Newer Older
1
require 'digest/md5'
W
wycats 已提交
2
require 'active_support/core_ext/class/attribute_accessors'
3
require 'monitor'
4

5
module ActionDispatch # :nodoc:
6 7 8 9 10
  # Represents an HTTP response generated by a controller action. Use it to
  # retrieve the current state of the response, or customize the response. It can
  # either represent a real HTTP response (i.e. one that is meant to be sent
  # back to the web browser) or a TestResponse (i.e. one that is generated
  # from integration tests).
P
Pratik Naik 已提交
11
  #
12
  # \Response is mostly a Ruby on \Rails framework implementation detail, and
13 14 15 16
  # 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 已提交
17
  #
18
  # Nevertheless, integration tests may want to inspect controller responses in
19
  # more detail, and that's when \Response can be useful for application
20
  # developers. Integration test methods such as
J
Joshua Peek 已提交
21 22
  # ActionDispatch::Integration::Session#get and
  # ActionDispatch::Integration::Session#post return objects of type
23
  # TestResponse (which are of course also of type \Response).
P
Pratik Naik 已提交
24
  #
25
  # For example, the following demo integration test prints the body of the
P
Pratik Naik 已提交
26 27
  # controller response to the console:
  #
J
Joshua Peek 已提交
28
  #  class DemoControllerTest < ActionDispatch::IntegrationTest
P
Pratik Naik 已提交
29 30
  #    def test_print_root_path_to_console
  #      get('/')
A
Alexey Vakhov 已提交
31
  #      puts response.body
P
Pratik Naik 已提交
32 33
  #    end
  #  end
34
  class Response
35 36
    attr_accessor :request, :header
    attr_reader :status
37
    attr_writer :sending_file
P
Pratik Naik 已提交
38

39
    alias_method :headers=, :header=
40 41 42
    alias_method :headers,  :header

    delegate :[], :[]=, :to => :@header
43
    delegate :each, :to => :@stream
44 45 46 47 48 49 50 51 52

    # 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.
S
Santiago Pastorino 已提交
53 54
    attr_accessor :charset
    attr_reader   :content_type
55

56 57 58
    CONTENT_TYPE = "Content-Type".freeze
    SET_COOKIE   = "Set-Cookie".freeze
    LOCATION     = "Location".freeze
S
Santiago Pastorino 已提交
59

60
    cattr_accessor(:default_charset) { "utf-8" }
E
Egor Homakov 已提交
61
    cattr_accessor(:default_headers)
62

63 64
    include Rack::Response::Helpers
    include ActionDispatch::Http::Cache::Response
65
    include MonitorMixin
66

67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
    class Buffer # :nodoc:
      def initialize(response, buf)
        @response = response
        @buf      = buf
        @closed   = false
      end

      def write(string)
        raise IOError, "closed stream" if closed?

        @response.commit!
        @buf.push string
      end

      def each(&block)
        @buf.each(&block)
      end

      def close
        @response.commit!
        @closed = true
      end

      def closed?
        @closed
      end
    end

    attr_reader :stream

97
    def initialize(status = 200, header = {}, body = [])
98 99
      super()

E
Egor Homakov 已提交
100 101 102 103
      if self.class.default_headers.respond_to?(:merge)
        header = self.class.default_headers.merge(header)
      end

104
      self.body, self.header, self.status = body, header, status
105

106
      @sending_file = false
107 108 109
      @blank        = false
      @cv           = new_cond
      @committed    = false
110 111
      @content_type = nil
      @charset      = nil
J
Joshua Peek 已提交
112

113
      if content_type = self[CONTENT_TYPE]
114 115
        type, charset = content_type.split(/;\s*charset=/)
        @content_type = Mime::Type.lookup(type)
116
        @charset = charset || self.class.default_charset
117
      end
118

119 120 121 122
      prepare_cache_control!

      yield self if block_given?
    end
123

124 125 126 127 128 129 130 131 132 133 134 135 136 137
    def await_commit
      synchronize do
        @cv.wait_until { @committed }
      end
    end

    def commit!
      synchronize do
        @committed = true
        @cv.broadcast
      end
    end

    def committed?
138
      @committed
139 140
    end

141
    def status=(status)
142
      @status = Rack::Utils.status_code(status)
143 144
    end

S
Santiago Pastorino 已提交
145 146 147 148
    def content_type=(content_type)
      @content_type = content_type.to_s
    end

149 150
    # The response code of the request
    def response_code
151
      @status
152 153 154 155
    end

    # Returns a String to ensure compatibility with Net::HTTPResponse
    def code
156
      @status.to_s
157 158 159
    end

    def message
160
      Rack::Utils::HTTP_STATUS_CODES[@status]
161
    end
162
    alias_method :status_message, :message
163

164 165
    def respond_to?(method)
      if method.to_sym == :to_path
166
        stream.respond_to?(:to_path)
167 168 169 170 171 172
      else
        super
      end
    end

    def to_path
173
      stream.to_path
174 175
    end

176
    def body
177 178 179
      strings = []
      each { |part| strings << part.to_s }
      strings.join
180
    end
181

Y
Yehuda Katz 已提交
182 183
    EMPTY = " "

184
    def body=(body)
Y
Yehuda Katz 已提交
185
      @blank = true if body == EMPTY
186

187 188 189 190 191
      if body.respond_to?(:to_path)
        @stream = body
      else
        @stream = build_buffer self, munge_body_object(body)
      end
192 193 194
    end

    def body_parts
195 196 197
      parts = []
      @stream.each { |x| parts << x }
      parts
D
Initial  
David Heinemeier Hansson 已提交
198 199
    end

200 201 202 203 204 205 206 207
    def set_cookie(key, value)
      ::Rack::Utils.set_cookie_header!(header, key, value)
    end

    def delete_cookie(key, value={})
      ::Rack::Utils.delete_cookie_header!(header, key, value)
    end

208
    def location
209
      headers[LOCATION]
210 211
    end
    alias_method :redirect_url, :location
212

213
    def location=(url)
214
      headers[LOCATION] = url
215
    end
216

217
    def close
218
      stream.close if stream.respond_to?(:close)
219 220
    end

221
    def to_a
222
      rack_response @status, @header.to_hash
223
    end
224 225
    alias prepare! to_a
    alias to_ary   to_a # For implicit splat on 1.9.2
226

227 228 229 230 231
    # Returns the response cookies, converted to a Hash of (name => value) pairs
    #
    #   assert_equal 'AuthorOfNewPage', r.cookies['author']
    def cookies
      cookies = {}
232
      if header = self[SET_COOKIE]
233 234 235 236 237 238 239
        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
240 241 242 243
      end
      cookies
    end

244
  private
J
Joshua Peek 已提交
245

246 247 248 249 250 251 252 253
    def build_buffer(response, body)
      Buffer.new response, body
    end

    def munge_body_object(body)
      body.respond_to?(:each) ? body : [body]
    end

254
    def assign_default_content_type_and_charset!(headers)
255
      return if headers[CONTENT_TYPE].present?
J
Joshua Peek 已提交
256

257 258
      @content_type ||= Mime::HTML
      @charset      ||= self.class.default_charset
J
Joshua Peek 已提交
259

260 261
      type = @content_type.to_s.dup
      type << "; charset=#{@charset}" unless @sending_file
J
Joshua Peek 已提交
262

263 264
      headers[CONTENT_TYPE] = type
    end
265 266 267 268 269 270 271 272 273 274 275 276 277 278

    def rack_response(status, header)
      assign_default_content_type_and_charset!(header)
      handle_conditional_get!

      header[SET_COOKIE] = header[SET_COOKIE].join("\n") if header[SET_COOKIE].respond_to?(:join)

      if [204, 304].include?(@status)
        header.delete CONTENT_TYPE
        [status, header, []]
      else
        [status, header, self]
      end
    end
D
Initial  
David Heinemeier Hansson 已提交
279
  end
280
end