代码之家  ›  专栏  ›  技术社区  ›  James A. Rosen

如何在Rails URL中使用UTF?

  •  2
  • James A. Rosen  · 技术社区  · 15 年前

    我有下面的路线 routes.rb :

    map.resources 'protégés', :controller => 'Proteges', :only => [:index]
    #
    # this version doesn't work any better:
    # map.resources 'proteges', :as => 'protégés', :only => [:index]
    

    当我去“ http://localhost:3000/protégés “我得到以下信息:

    No route matches "/prot%C3%A9g%C3%A9s" with {:method=>:get}
    

    我发现我使用的HTTP服务器(Mongrel)没有正确地解包。我也试过与乘客阿帕奇没有任何效果。我尝试添加机架中间件:

    require 'cgi'
    
    class UtfUrlMiddleware
    
      def initialize(app)
        @app = app
      end
    
      def call(env)
        request = Rack::Request.new(env)
        puts "before: #{request.path_info}"
        if request.path_info =~ /%[0-9a-fA-F]/
          request.path_info = CGI.unescape(request.path_info)
        end
        puts "after:  #{request.path_info}"
        @app.call(env)
      end
    
    end
    

    我在日志中看到了正确的信息:

    before: /prot%C3%A9g%C3%A9s
    after:  /protégés
    

    但我仍然看到相同的“没有路由匹配”错误。

    如何说服Rails使用国际化路线?我在2.3.5号轨道上,为了它的价值。

    1 回复  |  直到 15 年前
        1
  •  1
  •   James A. Rosen    15 年前

    问题是Rails使用 "REQUEST_URI" 环境变量。因此,以下工作:

    # in UtfUrlMiddleware:
    def call(env)
      if env['REQUEST_URI'] =~ /%[0-9a-fA-F]/
        env['REQUEST_URI'] = CGI.unescape(env['REQUEST_URI'])
      end
      @app.call(env)
    end
    
    推荐文章