/
redirect.rb
59 lines (57 loc) · 1.42 KB
/
redirect.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
module Hanami
module Action
# HTTP redirect API
#
# @since 0.1.0
module Redirect
# The HTTP header for redirects
#
# @since 0.2.0
# @api private
LOCATION = 'Location'.freeze
private
# Redirect to the given URL and halt the request
#
# @param url [String] the destination URL
# @param status [Fixnum] the http code
#
# @since 0.1.0
#
# @see Hanami::Action::Throwable#halt
#
# @example With default status code (302)
# require 'hanami/controller'
#
# class Create
# include Hanami::Action
#
# def call(params)
# # ...
# redirect_to 'http://example.com/articles/23'
# end
# end
#
# action = Create.new
# action.call({}) # => [302, {'Location' => '/articles/23'}, '']
#
# @example With custom status code
# require 'hanami/controller'
#
# class Create
# include Hanami::Action
#
# def call(params)
# # ...
# redirect_to 'http://example.com/articles/23', status: 301
# end
# end
#
# action = Create.new
# action.call({}) # => [301, {'Location' => '/articles/23'}, '']
def redirect_to(url, status: 302)
headers[LOCATION] = ::String.new(url)
halt(status)
end
end
end
end