Phi*_*han 3 ruby uri escaping sinatra ruby-1.9.3
我正在使用Sinatra并使用该get '/foo/:bar' {}方法从url获取参数.不幸的是,由于没有路由匹配/ ,因此其中的值:bar可能包含/导致404的讨厌内容/foo/:bar/baz.我URI.escape用来转义URL参数,但它认为/有效的有效字符.正如这里提到的那样,这是因为要检查的默认Regexp不区分不安全字符和保留字符.我想改变这个并做到这一点:
URI.escape("foo_<_>_&_3_#_/_+_%_bar", Regexp.union(URI::REGEXP::UNSAFE, '/'))
Run Code Online (Sandbox Code Playgroud)
只是为了测试它.
URI::REGEXP::UNSAFE是根据Ruby 1.9.3 Documentaton匹配的默认正则表达式:
escape(*arg)
Synopsis
URI.escape(str [, unsafe])
Args
str
String to replaces in.
unsafe
Regexp that matches all symbols that must be replaced with
codes. By default uses REGEXP::UNSAFE. When this argument is
a String, it represents a character set.
Description
Escapes the string, replacing all unsafe characters with codes.
Run Code Online (Sandbox Code Playgroud)
不幸的是我收到了这个错误:
uninitialized constant URI::REGEXP::UNSAFE
Run Code Online (Sandbox Code Playgroud)
正如这个GitHub问题所暗示的那样,这个Regexp已经从Ruby中删除了1.9.3.不幸的是,URI模块文档通常有点糟糕,但我真的无法弄清楚这一点.任何提示?
提前致谢!
URI#escape不是你想要的.你想要CGI#escape:
require 'cgi'
CGI.escape("foo_<_>_&_3_#_/_+_%_bar")
# => "foo_%3C_%3E_%26_3_%23_%2F_%2B_%25_bar"
Run Code Online (Sandbox Code Playgroud)
这将正确编码它以允许Sinatra检索它.