不确定如何解决 Rubocop的 Lint/UriEscapeUnescape警告
尝试将URI
替换为CGI
,认为这是“即插即用”的替换,但是却炸毁了测试套件。
以下是错误,后面是使用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
的替代品。有想法吗?
答案 0 :(得分:0)
遇到同样的问题,可以使用addressable lib来解决。
escaped_query = URI.escape(search,
Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
#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.
解决者:
addressable
或gemspec
中的Gemfile
宝石。gem 'addressable', '~> 2.7'
需要addressable/uri
添加适当的内容。
escaped_query = Addressable::URI.encode_component(search, Addressable::URI::CharacterClasses::QUERY)