Module: ActionDispatch::Routing::Redirection
- Included in:
- Mapper
- Defined in:
- lib/action_dispatch/routing/redirection.rb
Instance Method Summary collapse
-
#redirect(*args, &block) ⇒ Object
Redirect any path to another path:.
Instance Method Details
#redirect(*args, &block) ⇒ Object
Redirect any path to another path:
get "/stories" => redirect("/posts")
You can also use interpolation in the supplied redirect argument:
get 'docs/:article', to: redirect('/wiki/%{article}')
Note that if you return a path without a leading slash then the url is prefixed with the current SCRIPT_NAME environment variable. This is typically ‘/’ but may be different in a mounted engine or where the application is deployed to a subdirectory of a website.
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.
get 'jokes/:number', to: redirect { |params, request|
path = (params[:number].to_i.even? ? "wheres-the-beef" : "i-love-lamp")
"http://#{request.host_with_port}/#{path}"
}
Note that the do end syntax for the redirect block wouldn’t work, as Ruby would pass the block to get
instead of redirect
. Use { ... }
instead.
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.
get 'stores/:name', to: redirect(subdomain: 'stores', path: '/%{name}')
get '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.
get 'accounts/:name' => redirect(SubdomainRedirector.new('api'))
176 177 178 179 180 181 182 183 184 185 186 187 |
# File 'lib/action_dispatch/routing/redirection.rb', line 176 def redirect(*args, &block) = args. status = .delete(:status) || 301 path = args.shift return OptionRedirect.new(status, ) if .any? return PathRedirect.new(status, path) if String === path block = path if path.respond_to? :call raise ArgumentError, "redirection argument not supported" unless block Redirect.new status, block end |