response.rb 5.9 KB
Newer Older
1
require 'digest/md5'
J
Jeremy Kemper 已提交
2
require 'active_support/core_ext/module/delegation'
3
require 'active_support/core_ext/object/blank'
W
wycats 已提交
4
require 'active_support/core_ext/class/attribute_accessors'
5
require 'monitor'
6

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

41
    alias_method :headers=, :header=
42 43 44 45 46 47 48 49 50 51 52 53 54
    alias_method :headers,  :header

    delegate :[], :[]=, :to => :@header
    delegate :each, :to => :@body

    # 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 已提交
55 56
    attr_accessor :charset
    attr_reader   :content_type
57

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

62
    cattr_accessor(:default_charset) { "utf-8" }
63

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

68
    def initialize(status = 200, header = {}, body = [])
69 70
      super()

71
      self.body, self.header, self.status = body, header, status
72

73
      @sending_file = false
74 75 76
      @blank        = false
      @cv           = new_cond
      @committed    = false
J
Joshua Peek 已提交
77

78
      if content_type = self[CONTENT_TYPE]
79 80
        type, charset = content_type.split(/;\s*charset=/)
        @content_type = Mime::Type.lookup(type)
81
        @charset = charset || self.class.default_charset
82
      end
83

84 85 86 87
      prepare_cache_control!

      yield self if block_given?
    end
88

89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
    def await_commit
      synchronize do
        @cv.wait_until { @committed }
      end
    end

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

    def committed?
      synchronize { @committed }
    end

106
    def status=(status)
107
      @status = Rack::Utils.status_code(status)
108 109
    end

S
Santiago Pastorino 已提交
110 111 112 113
    def content_type=(content_type)
      @content_type = content_type.to_s
    end

114 115
    # The response code of the request
    def response_code
116
      @status
117 118 119 120
    end

    # Returns a String to ensure compatibility with Net::HTTPResponse
    def code
121
      @status.to_s
122 123 124
    end

    def message
125
      Rack::Utils::HTTP_STATUS_CODES[@status]
126
    end
127
    alias_method :status_message, :message
128

129 130 131 132 133 134 135 136 137 138 139 140
    def respond_to?(method)
      if method.to_sym == :to_path
        @body.respond_to?(:to_path)
      else
        super
      end
    end

    def to_path
      @body.to_path
    end

141
    def body
142 143 144
      strings = []
      each { |part| strings << part.to_s }
      strings.join
145
    end
146

Y
Yehuda Katz 已提交
147 148
    EMPTY = " "

149
    def body=(body)
Y
Yehuda Katz 已提交
150
      @blank = true if body == EMPTY
151

152
      @body = body.respond_to?(:each) ? body : [body]
153 154 155 156
    end

    def body_parts
      @body
D
Initial  
David Heinemeier Hansson 已提交
157 158
    end

159 160 161 162 163 164 165 166
    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

167
    def location
168
      headers[LOCATION]
169 170
    end
    alias_method :redirect_url, :location
171

172
    def location=(url)
173
      headers[LOCATION] = url
174
    end
175

176 177 178 179
    def close
      @body.close if @body.respond_to?(:close)
    end

180
    def to_a
181
      assign_default_content_type_and_charset!
182
      handle_conditional_get!
183

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

186
      if [204, 304].include?(@status)
187
        @header.delete CONTENT_TYPE
188
        [@status, @header, []]
189
      else
190
        [@status, @header, self]
191 192
      end
    end
193 194
    alias prepare! to_a
    alias to_ary   to_a # For implicit splat on 1.9.2
195

196 197 198 199 200
    # Returns the response cookies, converted to a Hash of (name => value) pairs
    #
    #   assert_equal 'AuthorOfNewPage', r.cookies['author']
    def cookies
      cookies = {}
201
      if header = self[SET_COOKIE]
202 203 204 205 206 207 208
        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
209 210 211 212
      end
      cookies
    end

213
  private
J
Joshua Peek 已提交
214

215 216
    def assign_default_content_type_and_charset!
      return if headers[CONTENT_TYPE].present?
J
Joshua Peek 已提交
217

218 219
      @content_type ||= Mime::HTML
      @charset      ||= self.class.default_charset
J
Joshua Peek 已提交
220

221 222
      type = @content_type.to_s.dup
      type << "; charset=#{@charset}" unless @sending_file
J
Joshua Peek 已提交
223

224 225
      headers[CONTENT_TYPE] = type
    end
D
Initial  
David Heinemeier Hansson 已提交
226
  end
227
end