【问题标题】:Matching URLs with a trailing slash in Rails' routes.rb在 Rails 的 routes.rb 中匹配带有斜杠的 URL
【发布时间】:2013-02-04 21:50:00
【问题描述】:

有没有办法在 Rails 的 routes.rb 中根据请求 URL 是否有斜杠来执行不同的路由?这似乎很困难,因为请求对象的尾部斜杠被删除,这意味着http://www.example.com/about/ 的 GET 具有http://www.example.com/about 的 request.url 值。这种行为会阻止使用request-based constraintsroute-globbing 进行匹配。

【问题讨论】:

    标签: ruby-on-rails url-routing


    【解决方案1】:

    我找到的一个解决方案是使用 request.env["REQUEST_URI"],其中包含随请求提交的原始 URL。不幸的是,由于它不是请求的直接字符串属性,因此需要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
    

    这似乎有点过头了,所以希望有人有更优雅的方法。

    【讨论】:

      猜你喜欢
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-13
      相关资源
      最近更新 更多