我正在使用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.escape和URI.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这个用例有什么好的替代品?
实际上替代品有所下降。
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。
目前 Ruby 标准库中没有官方的符合 RFC 3986 的 URI 转义器。
请参阅为什么 URI.escape() 被标记为过时以及此 REGEXP::UNSAFE 常量在哪里?为背景。
正如您在评论中发现并指出的那样,有几种方法存在各种问题:
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
| 归档时间: |
|
| 查看次数: |
1651 次 |
| 最近记录: |