views:

385

answers:

2

Is there a simpler way of writing this:

  map.old_site_cusom_packages '/customs_packages_options.html', :controller => :public, :action => :redirect_to_home
  map.old_corporate '/corporate.html', :controller => :public, :action => :redirect_to_home
  map.old_track '/track.html', :controller => :public, :action => :redirect_to_home
  map.old_links '/links.html', :controller => :public, :action => :redirect_to_home
  map.old_contact '/contact.html', :controller => :public, :action => :redirect_to_home

I want to send many named routes to one action on one controller, I'm making sure url's left over from an old site redirect to the correct pages.

Cheers.

+6  A: 

Use the with_options method:

map.with_options :controller => :public, :action => :redirect_to_home do |p|
  p.old_site_custom_packages '/customs_packages_options.html'
  p.old_corporate '/corporate.html'
  p.old_track '/track.html'
  p.old_links '/links.html'
  p.old_contact '/contact.html'
end
John Topley
+1  A: 

You can always write a multi-purpose route with a regular expression to capture the details:

old_content_names_regexp = Regexp.new(%w[
  customs_packages_options
  corporate
  track
  links
  contact
].join('|'))

map.old_content '/:page_name.html',
  :controller => :public,
  :action => :redirect_to_home,
  :requirements => {
    :page_name => old_content_names_regexp
  }

That should capture specific pages and redirect them accordingly. A more robust solution is to have some kind of lookup table in a database that is checked before serving any content or 404-type pages.

Edit: For named routes, it's an easy alteration:

%w[
  customs_packages_options
  corporate
  track
  links
  contact
].each do |old_path|
  map.send(:"old_#{old_path}",
    "/#{old_path}.html",
    :controller => :public,
    :action => :redirect_to_home,
  )
end

In most cases the old routes can be rewritten using the singular legacy route listed first. It's also best to keep the routing table as trim as possible. The second method is more of a crutch to try and bridge the old routes.

tadman
Perfect... and to make it even more succinct you don't need to create the regex object you can just do...old_content_names_regexp = /customs_packages_options|home|track/
Smickie
Whilst neat, this doesn't actually do what is asked for. It provides one named route that is parameterized with a `page_name`. The question referred to many named routes.
John Topley
It doesn't provide the same named-routes functionality, but that's easy to add.
tadman
The reason for creating the regexp independently of the route is if things get really crazy, where you have dozens of entries, it will be maintainable. Since the routing table configuration is all Ruby, you can even read that data in from another source such as a text-file to meta-program your routes.
tadman