class ActionDispatch::Response
Action Dispatch Response
Представляет HTTP-ответ, сформированный действием контроллера. Используйте его, чтобы получить текущее состояние ответа или настроить его. Он может представлять как реальный HTTP-ответ (то есть предназначенный для отправки обратно в веб-браузер), так и TestResponse (то есть сгенерированный интеграционными тестами).
Объект Response для текущего запроса доступен в контроллерах как ActionController::Metal#response. ActionController::Metal также предоставляет несколько дополнительных методов, делегирующих атрибутам объекта Response, например ActionController::Metal#headers.
В тестах Integration, вероятно, также потребуется подробнее изучить ответы. Для этого такие методы, как Integration::RequestHelpers#get и Integration::RequestHelpers#post, возвращают экземпляры TestResponse (унаследованного от Response).
Например, следующий демонстрационный интеграционный тест выводит тело ответа контроллера в консоль:
class DemoControllerTest < ActionDispatch::IntegrationTest
def test_print_root_path_to_console
get('/')
puts response.body
end
end
Константы
- CONTENT_TYPE
- ContentTypeHeader
- Header
-
Устаревает:
- Headers
- NO_CONTENT_CODES
- NullContentTypeHeader
- SET_COOKIE
Атрибуты
Заголовки ответа.
header["Content-Type"] # => "text/plain" header["Content-Type"] = "application/json" header["Content-Type"] # => "application/json"
Также имеет псевдоним headers.
headers["Content-Type"] # => "text/plain" headers["Content-Type"] = "application/json" headers["Content-Type"] # => "application/json"
Для совместимости также имеет псевдоним header.
Заголовки ответа.
header["Content-Type"] # => "text/plain" header["Content-Type"] = "application/json" header["Content-Type"] # => "application/json"
Также имеет псевдоним headers.
headers["Content-Type"] # => "text/plain" headers["Content-Type"] = "application/json" headers["Content-Type"] # => "application/json"
Для совместимости также имеет псевдоним header.
Запрос, на который отвечает данный ответ.
Код состояния HTTP.
Базовое тело в виде объекта, поддерживающего потоковую передачу.
Открытые методы класса
# File actionpack/lib/action_dispatch/http/response.rb, line 185
def self.create(status = 200, headers = {}, body = [], default_headers: self.default_headers)
headers = merge_default_headers(headers, default_headers)
new status, headers, body
end # File actionpack/lib/action_dispatch/http/response.rb, line 190 def self.merge_default_headers(original, default) default.respond_to?(:merge) ? default.merge(original) : original end
# File actionpack/lib/action_dispatch/http/response.rb, line 197
def initialize(status = 200, headers = nil, body = [])
super()
@headers = Headers.new
headers&.each do |key, value|
@headers[key] = value
end
self.body, self.status = body, status
@cv = new_cond
@committed = false
@sending = false
@sent = false
prepare_cache_control!
yield self if block_given?
end Открытые методы экземпляра
# File actionpack/lib/action_dispatch/http/response.rb, line 446
def abort
if stream.respond_to?(:abort)
stream.abort
elsif stream.respond_to?(:close)
# `stream.close` should really be reserved for a close from the other direction,
# but we must fall back to it for compatibility.
stream.close
end
end # File actionpack/lib/action_dispatch/http/response.rb, line 223
def await_commit
synchronize do
@cv.wait_until { @committed }
end
end # File actionpack/lib/action_dispatch/http/response.rb, line 229
def await_sent
synchronize { @cv.wait_until { @sent } }
end # File actionpack/lib/action_dispatch/http/response.rb, line 369
def body
if @stream.respond_to?(:to_ary)
@stream.to_ary.join
elsif @stream.respond_to?(:body)
@stream.body
else
@stream
end
end Возвращает содержимое ответа в виде строки. Она содержит данные всех вызовов render.
# File actionpack/lib/action_dispatch/http/response.rb, line 384
def body=(body)
# Prevent ActionController::Metal::Live::Response from committing the response prematurely.
synchronize do
if body.respond_to?(:to_str)
@stream = build_buffer(self, [body])
elsif body.respond_to?(:to_path)
@stream = body
elsif body.respond_to?(:to_ary)
@stream = build_buffer(self, body)
else
@stream = body
end
end
end Позволяет вручную задать или переопределить тело ответа.
# File actionpack/lib/action_dispatch/http/response.rb, line 433
def body_parts
parts = []
@stream.each { |x| parts << x }
parts
end # File actionpack/lib/action_dispatch/http/response.rb, line 339 def charset header_info = parsed_content_type_header header_info.charset || self.class.default_charset end
Кодировка ответа. HTML должен знать кодировку передаваемого ему содержимого, поэтому мы должны указать её.
# File actionpack/lib/action_dispatch/http/response.rb, line 328
def charset=(charset)
content_type = parsed_content_type_header.mime_type
if false == charset
set_content_type content_type, nil
else
set_content_type content_type, charset || self.class.default_charset
end
end Задаёт набор символов HTTP. Если параметр равен nil, набор символов устанавливается в default_charset.
response.charset = 'utf-16' # => 'utf-16' response.charset = nil # => 'utf-8'
# File actionpack/lib/action_dispatch/http/response.rb, line 442 def close stream.close if stream.respond_to?(:close) end
# File actionpack/lib/action_dispatch/http/response.rb, line 350 def code @status.to_s end
Возвращает строку для обеспечения совместимости с Net::HTTPResponse.
# File actionpack/lib/action_dispatch/http/response.rb, line 233
def commit!
synchronize do
before_committed
@committed = true
@cv.broadcast
end
end # File actionpack/lib/action_dispatch/http/response.rb, line 257
def committed?; synchronize { @committed }; end # File actionpack/lib/action_dispatch/http/response.rb, line 308 def content_type super.presence end
Тип содержимого ответа.
# File actionpack/lib/action_dispatch/http/response.rb, line 289
def content_type=(content_type)
case content_type
when NilClass
return
when Symbol
mime_type = Mime[content_type]
raise ArgumentError, "Unknown MIME type #{content_type}" unless mime_type
new_header_info = ContentTypeHeader.new(mime_type.to_s)
else
new_header_info = parse_content_type(content_type.to_s)
end
prev_header_info = parsed_content_type_header
charset = new_header_info.charset || prev_header_info.charset
charset ||= self.class.default_charset unless prev_header_info.mime_type
set_content_type new_header_info.mime_type, charset
end Задаёт MIME-тип содержимого HTTP-ответа. Например, в контроллере можно написать следующее:
response.content_type = "text/html"
Этот метод также принимает символ с расширением MIME-типа:
response.content_type = :html
Если для этого ответа задан набор символов (см. charset=), сведения о наборе символов также будут включены в информацию о типе содержимого.
# File actionpack/lib/action_dispatch/http/response.rb, line 469
def cookies
cookies = {}
if header = get_header(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
end
cookies
end Возвращает файлы cookie ответа, преобразованные в Hash пар (имя => значение).
assert_equal 'AuthorOfNewPage', r.cookies['author']
# File actionpack/lib/action_dispatch/http/response.rb, line 221 def delete_header(key); @headers.delete key; end
# File actionpack/lib/action_dispatch/http/response.rb, line 91 def each(&block) sending! x = @stream.each(&block) sent! x end
# File actionpack/lib/action_dispatch/http/response.rb, line 219 def get_header(key); @headers[key]; end
# File actionpack/lib/action_dispatch/http/response.rb, line 218 def has_header?(key); @headers.key? key; end
# File actionpack/lib/action_dispatch/http/response.rb, line 261
Адрес ответа.
# File actionpack/lib/action_dispatch/http/response.rb, line 266
Задаёт адрес ответа.
# File actionpack/lib/action_dispatch/http/response.rb, line 313 def media_type parsed_content_type_header.mime_type end
Тип данных ответа.
# File actionpack/lib/action_dispatch/http/response.rb, line 362 def message Rack::Utils::HTTP_STATUS_CODES[@status] end
Возвращает соответствующее сообщение для текущего кода состояния HTTP:
response.status = 200 response.message # => "OK" response.status = 404 response.message # => "Not Found"
# File actionpack/lib/action_dispatch/http/response.rb, line 429 def reset_body! @stream = build_buffer(self, []) end
# File actionpack/lib/action_dispatch/http/response.rb, line 345 def response_code @status end
Код ответа на запрос.
# File actionpack/lib/action_dispatch/http/response.rb, line 424 def send_file(path) commit! @stream = FileBody.new(path) end
Отправляет файл, хранящийся по адресу path, в качестве тела ответа.
# File actionpack/lib/action_dispatch/http/response.rb, line 241
def sending!
synchronize do
before_sending
@sending = true
@cv.broadcast
end
end # File actionpack/lib/action_dispatch/http/response.rb, line 256
def sending?; synchronize { @sending }; end # File actionpack/lib/action_dispatch/http/response.rb, line 317
def sending_file=(v)
if true == v
self.charset = false
end
end # File actionpack/lib/action_dispatch/http/response.rb, line 249
def sent!
synchronize do
@sent = true
@cv.broadcast
end
end # File actionpack/lib/action_dispatch/http/response.rb, line 258
def sent?; synchronize { @sent }; end # File actionpack/lib/action_dispatch/http/response.rb, line 220 def set_header(key, v); @headers[key] = v; end
# File actionpack/lib/action_dispatch/http/response.rb, line 273 def status=(status) @status = Response.rack_status_code(status) end
Задаёт код состояния HTTP.
# File actionpack/lib/action_dispatch/http/response.rb, line 460 def to_a commit! rack_response @status, @headers.to_hash end
Преобразует Response в совместимый с Rack массив, содержащий состояние, заголовки и тело. Позволяет явно распаковать массив:
status, headers, body = *response
# File actionpack/lib/action_dispatch/http/response.rb, line 379 def write(string) @stream.write string end
© 2004–2021 David Heinemeier Hansson
Licensed under the MIT License.