Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails, routing many named routes to one action

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.

like image 613
MintDeparture Avatar asked Feb 17 '10 15:02

MintDeparture


2 Answers

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
like image 155
John Topley Avatar answered Nov 08 '22 15:11

John Topley


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.

like image 24
tadman Avatar answered Nov 08 '22 16:11

tadman