Matching trailing slash URLs in Rails.rb routes

Is there a way to do other routing on Rails.rb routes depending on whether the request URL has a trailing slash? This seems difficult, since the request object has its end slash, which means GET http://www.example.com/about/ has the value request.url http://www.example.com/about . This behavior prevents matching using query-based constraints as well as route-globbing .

+1
source share
1 answer

One of the solutions I found is to use request.env ["REQUEST_URI"], which contains the raw URL sent with the request. Unfortunately, since it is not a direct string property of a request, it requires a custom mapping 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

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

+1
source

Source: https://habr.com/ru/post/1546903/


All Articles