response.rb 6.7 KB
Newer Older
1
require 'digest/md5'
J
Jeremy Kemper 已提交
2
require 'active_support/core_ext/module/delegation'
3

4
module ActionDispatch # :nodoc:
5 6 7 8 9 10
  # 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 已提交
11
  #
12 13 14 15 16
  # 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 已提交
17
  #
18 19 20 21 22 23
  # 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 已提交
24 25 26 27 28 29 30 31 32 33
  #
  # 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
34
  class Response < Rack::Response
35 36 37 38 39 40 41 42 43 44 45
    class SimpleHeaderHash < Hash
      def to_hash
        result = {}
        each do |k,v|
          v = v.join("\n") if v.is_a?(Array)
          result[k] = v
        end
        result
      end
    end

46
    attr_accessor :request
47
    attr_reader :cache_control
P
Pratik Naik 已提交
48

49
    attr_writer :header, :sending_file
50 51
    alias_method :headers=, :header=

D
Initial  
David Heinemeier Hansson 已提交
52
    def initialize
53 54
      @status = 200
      @header = SimpleHeaderHash.new
55
      @cache_control = {}
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70

      @writer = lambda { |x| @body << x }
      @block = nil
      @length = 0

      @body = []
      @sending_file = false

      yield self if block_given?
    end

    def write(str)
      s = str.to_s
      @writer.call s
      str
71
    end
72

73 74 75 76
    def status=(status)
      @status = status.to_i
    end

77 78
    # The response code of the request
    def response_code
79
      @status
80 81 82 83
    end

    # Returns a String to ensure compatibility with Net::HTTPResponse
    def code
84
      @status.to_s
85 86 87
    end

    def message
88
      StatusCodes::STATUS_CODES[@status]
89
    end
90
    alias_method :status_message, :message
91

92 93 94 95 96
    def body
      str = ''
      each { |part| str << part.to_s }
      str
    end
97

98
    def body=(body)
99
      @body = body.respond_to?(:to_str) ? [body] : body
100 101 102 103
    end

    def body_parts
      @body
D
Initial  
David Heinemeier Hansson 已提交
104 105
    end

106 107 108 109
    def location
      headers['Location']
    end
    alias_method :redirect_url, :location
110

111 112 113
    def location=(url)
      headers['Location'] = url
    end
114

P
Pratik Naik 已提交
115 116 117 118 119 120 121 122
    # 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.
123
    attr_accessor :charset, :content_type
124

125
    def last_modified
126 127 128 129 130 131 132
      if last = headers['Last-Modified']
        Time.httpdate(last)
      end
    end

    def last_modified?
      headers.include?('Last-Modified')
133
    end
134

135 136
    def last_modified=(utc_time)
      headers['Last-Modified'] = utc_time.httpdate
137
    end
138

139 140 141
    def etag
      headers['ETag']
    end
142

143 144 145
    def etag?
      headers.include?('ETag')
    end
146

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

155 156 157
    CONTENT_TYPE    = "Content-Type"

    cattr_accessor(:default_charset) { "utf-8" }
158 159

    def assign_default_content_type_and_charset!
160
      return if !headers[CONTENT_TYPE].blank?
161 162

      @content_type ||= Mime::HTML
163
      @charset      ||= self.class.default_charset
164 165

      type = @content_type.to_s.dup
166
      type << "; charset=#{@charset}" unless @sending_file
167

168
      headers[CONTENT_TYPE] = type
169 170
    end

171
    def prepare!
172
      assign_default_content_type_and_charset!
173
      handle_conditional_get!
174
      self["Set-Cookie"] ||= ""
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 196 197 198 199
    # Returns the response cookies, converted to a Hash of (name => value) pairs
    #
    #   assert_equal 'AuthorOfNewPage', r.cookies['author']
    def cookies
      cookies = {}
200 201 202 203 204 205 206 207
      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
208 209 210 211
      end
      cookies
    end

212
    private
213
      def handle_conditional_get!
214
        if etag? || last_modified? || !cache_control.empty?
215 216
          set_conditional_cache_control!
        elsif nonempty_ok_response?
217
          self.etag = @body
218 219

          if request && request.etag_matches?(etag)
220
            self.status = 304
221
            self.body = []
222 223 224
          end

          set_conditional_cache_control!
225 226
        else
          headers["Cache-Control"] = "no-cache"
227
        end
228 229
      end

230 231
      EMPTY_RESPONSE = [" "]

232
      def nonempty_ok_response?
233
        ok = !@status || @status == 200
234
        ok && string_body? && @body != EMPTY_RESPONSE
J
Jeremy Kemper 已提交
235 236 237 238
      end

      def string_body?
        !body_parts.respond_to?(:call) && body_parts.any? && body_parts.all? { |part| part.is_a?(String) }
239 240
      end

241 242
      DEFAULT_CACHE_CONTROL = "max-age=0, private, must-revalidate"

243
      def set_conditional_cache_control!
244
        control = cache_control
245

246 247 248 249 250 251 252 253 254 255 256
        if control.empty?
          headers["Cache-Control"] = DEFAULT_CACHE_CONTROL
        else
          extras  = control[:extras]
          max_age = control[:max_age]

          options = []
          options << "max-age=#{max_age}" if max_age
          options << (control[:public] ? "public" : "private")
          options << "must-revalidate" if control[:must_revalidate]
          options.concat(extras) if extras
257

258 259
          headers["Cache-Control"] = options.join(", ")
        end
260

261
      end
D
Initial  
David Heinemeier Hansson 已提交
262
  end
263
end