首页 > 解决方案 > 替代 URI.escape 以避免 Lint/UriEscapeUnescape 警告?

问题描述

不确定如何修复Rubocop 的 Lint/UriEscapeUnescape警告

尝试用“插入式”替换URICGI想法替换,但这会炸毁测试套件。

这是错误,后面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因为您可能会相信列表错误。想法?

标签: ruby-on-railsrubyurlencodelintrubocop

解决方案


遇到同样的问题,通过使用可寻址库修复它。

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 addressablegemgemspecGemfile.
gem 'addressable', '~> 2.7'
  • 要求addressable/uri

  • 适当添加。

escaped_query = Addressable::URI.encode_component(search, Addressable::URI::CharacterClasses::QUERY)


推荐阅读