Matching URLs with a trailing slash in Rails' routes.rb

时光怂恿深爱的人放手 提交于 2019-12-11 11:07:34

问题


Is there a way to perform different routing in Rails' routes.rb depending on whether the request URL has a trailing slash? This seems difficult since the request object has its trailing slash removed, meaning a GET of http://www.example.com/about/ has a request.url value of http://www.example.com/about. That behavior prevents matching using request-based constraints as well as route-globbing.


回答1:


One solution I've found is to use request.env["REQUEST_URI"], which contains the raw URL submitted with the request. Unfortunately, since it's not a direct string property of the request, it requires a custom matching object:

class TrailingSlashMatcher
  def matches?(request)
    uri = request.env["REQUEST_URI"]
    !!uri && uri.end_with?("/")
  end
end

AppName::Application.routes.draw do
  match '/example/*path', constraints: TrailingSlashMatcher.new, to: redirect("/somewhere/")
end

That seems like overkill, so hopefully someone has a more elegant approach.



来源:https://stackoverflow.com/questions/14696281/matching-urls-with-a-trailing-slash-in-rails-routes-rb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!