【发布时间】:2018-10-17 16:57:19
【问题描述】:
不确定如何解决 Rubocop 的 Lint/UriEscapeUnescape 警告
尝试用 CGI 替换 URI,认为这是“直接”替换,但会炸毁测试套件。
下面是使用URI 的代码行后面的错误:
app/models/media_file.rb:76:5: W: Lint/UriEscapeUnescape: URI.escape method is obsolete and should not be used. Instead, use CGI.escape, URI.encode_www_form or URI.encode_www_form_component depending on your specific use case.
URI ...
^^^
# app/models/media_file.rb
...
def cdn_url(format: nil)
if format.nil?
"#{s3_config.cloudfront_endpoint}/#{escape_url(key)}"
elsif converted_urls.with_indifferent_access[format.to_s]
filename = converted_urls.with_indifferent_access[format.to_s]
if URI.parse(escape_url(filename)).host
filename
else
"#{s3_config.cloudfront_endpoint}/#{escape_url(filename)}"
end
else
converted(url)
end
end
...
private
def escape_url(url)
URI
.escape(url)
.gsub(/\(/, '%28')
.gsub(/\)/, '%29')
.gsub(/\[/, '%5B')
.gsub(/\]/, '%5D')
end
编辑:添加使用URI 和CGI 转义的字符串的示例输出:
url: images/medium/test-image.jpg
URI.escape(url): images/medium/test-image.jpg
CGI.escape(url): images%2Fmedium%2Ftest-image.jpg
url: images/medium/test-image.jpg
URI.escape(url): images/medium/test-image.jpg
CGI.escape(url): images%2Fmedium%2Ftest-image.jpg
看起来CGI 不是URI 的替代品,因为列表错误可能会让您相信。想法?
【问题讨论】:
-
为什么你的测试失败了?你测试什么 URL,你期望什么输出以及它返回什么?
-
警察清楚地告诉你该怎么做。如果
CGI.escape导致错误,您需要修复这些错误。我们无法为您提供帮助,因为您没有包含任何输入或它们导致的错误。 -
我添加了一些输出(上图),所以很明显
URI.escape和CGI.escape正在做不同的事情......那么,如果URI.escape是“过时的”,那么替换是什么? -
我推荐阅读the pull request that added it to rubocop。 TLDR:
URI.escape一直是deprecated in ruby trunk(这反映在in the docs),警察正在警告你。替代实现的细节留给读者,CGI是一个可能的例子。 -
CGI.escape不能替代URI.escape。例如:URI.escape('foo bar')给出'foo%20bar',而CGI.escape('foo bar')给出'foo+bar'。例如,如果您尝试转义包含空格的基本身份验证密码,则会导致问题。有一些解决方法,但建议 OP 在不一样的情况下使用CGI.escape并没有帮助。
标签: ruby-on-rails ruby urlencode lint rubocop