ruby-on-rails - 替代 URI.escape 以避免 Lint/UriEscapeUnescape 警告?
问题描述
不确定如何修复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
添加用and转义的字符串的示例输出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
因为您可能会相信列表错误。想法?
解决方案
遇到同样的问题,通过使用可寻址库修复它。
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.
解决者:
- gem
addressable
gemgemspec
或Gemfile
.
gem 'addressable', '~> 2.7'
要求
addressable/uri
适当添加。
escaped_query = Addressable::URI.encode_component(search, Addressable::URI::CharacterClasses::QUERY)
推荐阅读
- php - 错误:HTTP/2 成帧层中的流错误
- javascript - 如何列出firestore中的所有集合
- java - Android - 查看寻呼机返回功能在前两个选项卡中不起作用
- css - 带图标的引导进度条
- firebase - 以原子方式推送新的聊天消息并更新 Firebase 实时数据库上的 lastMessage 值
- jupyter-lab - Anaconda / Jupyter lab:更改目录后出现AttributeError
- sql - SQL server CASE 全选,但如果值为a,则其他列值不能为NULL
- c# - EF Core 5 - 使用 SQL 更新实体不起作用
- python - 如何使窗口始终位于顶部?
- ruby-on-rails - 在 JSON 响应中包含 ActiveStorage URL 到图像?