Ruby 2.7 说 URI.escape 已过时,用什么替代它?

Tad*_*kas 8 ruby

我正在使用URI.encode生成 HTML 数据 URL:

visit "data:text/html,#{URI::encode(html)}"
Run Code Online (Sandbox Code Playgroud)

升级到 Ruby 2.7.1 后,解释器开始警告:

warning: URI.escape is obsolete
Run Code Online (Sandbox Code Playgroud)

推荐的替代品是CGI.escapeURI.encode_www_form_component。然而,他们并没有做同样的事情:

2.7.1 :007 > URI.escape '<html>this and that</html>'
(irb):7: warning: URI.escape is obsolete
 => "%3Chtml%3Ethis%20and%20that%3C/html%3E"
2.7.1 :008 > CGI.escape '<html>this and that</html>'
 => "%3Chtml%3Ethis+and+that%3C%2Fhtml%3E"
2.7.1 :009 > URI.encode_www_form_component '<html>this and that</html>'
 => "%3Chtml%3Ethis+and+that%3C%2Fhtml%3E"
Run Code Online (Sandbox Code Playgroud)

这些轻微编码差异的结果 - html 页面,其中空格被替换为+. 我的问题是 -URI.encode这个用例有什么好的替代品?

Ste*_*ing 8

实际上替代品有所下降。

s = '<html>this and that</html>'    
p = URI::Parser.new
p.escape(s)
=> "%3Chtml%3Ethis%20and%20that%3C/html%3E"
Run Code Online (Sandbox Code Playgroud)

文档:https : //docs.w3cub.com/ruby~3/uri/rfc2396_parser

通过本文https://docs.knapsackpro.com/2020/uri-escape-is-obsolete-percent-encoding-your-query-string下的评论发现了这一点

还针对我的设置中的其他一些字符串对此进行了测试,与 .escape 相比,这似乎也以相同的方式保留了逗号ERB::Util.url_encode

  • 使用 `URI::Parser#escape` 与使用 `URI::escape` 完全一样,只是没有警告。如果这就是您想要的,那很好,但重要的是要认识到这不是一个不同的解决方案。如果你看一下源代码,`URI::escape`调用`URI::DEFAULT_PARSER.escape`,而`URI::DEFAULT_PARSER`是`URI::Parser`的一个实例。 (12认同)

D. *_* SM 6

目前 Ruby 标准库中没有官方的符合 RFC 3986 的 URI 转义器。

请参阅为什么 URI.escape() 被标记为过时以及此 REGEXP::UNSAFE 常量在哪里?为背景。

正如您在评论中发现并指出的那样,有几种方法存在各种问题:

  • 他们产生弃用警告
  • 他们不声称符合标准
  • 它们没有按照 RFC 3986 进行转义
  • 它们在切线相关的库中实现

  • 这似乎是 ruby​​ stdlib 中的一个奇怪的遗漏 (2认同)

gor*_*die 6

来自Apidock.com

require "erb"
include ERB::Util

puts url_encode("Programming Ruby:  The Pragmatic Programmer's Guide")
Run Code Online (Sandbox Code Playgroud)

生成

编程%20Ruby%3A%20%20The%20Pragmatic%20Programmer%27s%20Guide