- R
Redirect any path to another path:
match "/stories" => redirect("/posts")
You can also use interpolation in the supplied redirect argument:
match 'docs/:article', :to => redirect('/wiki/%{article}')
Alternatively you can use one of the other syntaxes:
The block version of redirect allows for the easy encapsulation of any logic associated with the redirect in question. Either the params and request are supplied as arguments, or just params, depending of how many arguments your block accepts. A string is required as a return value.
match 'jokes/:number', :to => redirect do |params, request| path = (params[:number].to_i.even? ? "/wheres-the-beef" : "/i-love-lamp") "http://#{request.host_with_port}/#{path}" end
The options version of redirect allows you to supply only the parts of the url which need to change, it also supports interpolation of the path similar to the first example.
match 'stores/:name', :to => redirect(:subdomain => 'stores', :path => '/%{name}') match 'stores/:name(*all)', :to => redirect(:subdomain => 'stores', :path => '/%{name}%{all}')
Finally, an object which responds to call can be supplied to redirect, allowing you to reuse common redirect routes. The call method must accept two arguments, params and request, and return a string.
match 'accounts/:name' => redirect(SubdomainRedirector.new('api'))
# File actionpack/lib/action_dispatch/routing/redirection.rb, line 98 98: def redirect(*args, &block) 99: options = args.last.is_a?(Hash) ? args.pop : {} 100: status = options.delete(:status) || 301 101: 102: return OptionRedirect.new(status, options) if options.any? 103: 104: path = args.shift 105: 106: block = lambda { |params, request| 107: (params.empty? || !path.match(/%\{\w*\}/)) ? path : (path % escape(params)) 108: } if String === path 109: 110: block = path if path.respond_to? :call 111: 112: # :FIXME: remove in Rails 4.0 113: if block && block.respond_to?(:arity) && block.arity < 2 114: msg = "redirect blocks with arity of #{block.arity} are deprecated. Your block must take 2 parameters: the environment, and a request object" 115: ActiveSupport::Deprecation.warn msg 116: deprecated_block = block 117: block = lambda { |params, _| deprecated_block.call(params) } 118: end 119: 120: raise ArgumentError, "redirection argument not supported" unless block 121: 122: Redirect.new status, block 123: end