提交 e48b4c2d 编写于 作者: Y Yehuda Katz

:to => redirect() can take a String using 1.9-style interpolation or proc that...

:to => redirect() can take a String using 1.9-style interpolation or proc that takes the path parameters as a Hash
上级 8b4735fb
......@@ -132,13 +132,19 @@ def delete(*args, &block)
map_method(:delete, *args, &block)
end
def redirect(path, options = {})
def redirect(*args, &block)
options = args.last.is_a?(Hash) ? args.pop : {}
path = args.shift || block
path_proc = path.is_a?(Proc) ? path : proc {|params| path % params }
status = options[:status] || 301
lambda { |env|
lambda do |env|
req = Rack::Request.new(env)
url = req.scheme + '://' + req.host + path
params = path_proc.call(env["action_dispatch.request.path_parameters"])
url = req.scheme + '://' + req.host + params
[status, {'Location' => url, 'Content-Type' => 'text/html'}, ['Moved Permanently']]
}
end
end
private
......
......@@ -24,6 +24,9 @@ def self.matches?(request)
match 'account/login', :to => redirect("/login")
match 'account/modulo/:name', :to => redirect("/%{name}s")
match 'account/proc/:name', :to => redirect {|params| "/#{params[:name].pluralize}" }
match 'openid/login', :via => [:get, :post], :to => "openid#login"
controller(:global) do
......@@ -145,6 +148,24 @@ def test_login_redirect
end
end
def test_redirect_modulo
with_test_routes do
get '/account/modulo/name'
assert_equal 301, @response.status
assert_equal 'http://www.example.com/names', @response.headers['Location']
assert_equal 'Moved Permanently', @response.body
end
end
def test_redirect_proc
with_test_routes do
get '/account/proc/person'
assert_equal 301, @response.status
assert_equal 'http://www.example.com/people', @response.headers['Location']
assert_equal 'Moved Permanently', @response.body
end
end
def test_openid
with_test_routes do
get '/openid/login'
......
......@@ -14,5 +14,6 @@
require 'active_support/core_ext/enumerable'
require 'active_support/core_ext/process/daemon'
require 'active_support/core_ext/string/conversions'
require 'active_support/core_ext/string/interpolation'
require 'active_support/core_ext/rexml'
require 'active_support/core_ext/time/conversions'
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册