From e48b4c2dd01877ace901e1c186d04605b53b40d0 Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Sun, 20 Dec 2009 14:07:19 -0800 Subject: :to => redirect() can take a String using 1.9-style interpolation or proc that takes the path parameters as a Hash --- actionpack/lib/action_dispatch/routing/mapper.rb | 14 ++++++++++---- actionpack/test/dispatch/routing_test.rb | 21 +++++++++++++++++++++ 2 files changed, 31 insertions(+), 4 deletions(-) (limited to 'actionpack') diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index d480af876d..57e992d7dc 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -132,13 +132,19 @@ module ActionDispatch 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 diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb index 425796b460..7145a0c530 100644 --- a/actionpack/test/dispatch/routing_test.rb +++ b/actionpack/test/dispatch/routing_test.rb @@ -24,6 +24,9 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest 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 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest 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' -- cgit v1.2.3