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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
require 'action_dispatch/http/request'
module ActionDispatch
module Routing
module Redirection
# Redirect any path to another path:
#
# match "/stories" => redirect("/posts")
def redirect(*args, &block)
options = args.last.is_a?(Hash) ? args.pop : {}
status = options.delete(:status) || 301
path = args.shift
path_proc = if path.is_a?(String)
proc { |params| (params.empty? || !path.match(/%\{\w*\}/)) ? path : (path % params) }
elsif options.any?
options_proc(options)
elsif path.respond_to?(:call)
proc { |params, request| path.call(params, request) }
elsif block
block
else
raise ArgumentError, "redirection argument not supported"
end
redirection_proc(status, path_proc)
end
private
def options_proc(options)
proc do |params, request|
path = if options[:path].nil?
request.path
elsif params.empty? || !options[:path].match(/%\{\w*\}/)
options.delete(:path)
else
(options.delete(:path) % params)
end
default_options = {
:protocol => request.protocol,
:host => request.host,
:port => request.optional_port,
:path => path,
:params => request.query_parameters
}
ActionDispatch::Http::URL.url_for(options.reverse_merge(default_options))
end
end
def redirection_proc(status, path_proc)
lambda do |env|
req = Request.new(env)
params = [req.symbolized_path_parameters]
params << req if path_proc.arity > 1
uri = URI.parse(path_proc.call(*params))
uri.scheme ||= req.scheme
uri.host ||= req.host
uri.port ||= req.port unless req.standard_port?
body = %(<html><body>You are being <a href="#{ERB::Util.h(uri.to_s)}">redirected</a>.</body></html>)
headers = {
'Location' => uri.to_s,
'Content-Type' => 'text/html',
'Content-Length' => body.length.to_s
}
[ status, headers, [body] ]
end
end
end
end
end
|