开发者

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开发者_如何学Python_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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜