【问题标题】:Replacement for URI.escape that avoids Lint/UriEscapeUnescape warnings?替代 URI.escape 以避免 Lint/UriEscapeUnescape 警告?
【发布时间】: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

编辑:添加使用URICGI 转义的字符串的示例输出:

            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.escapeCGI.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


【解决方案1】:

遇到同样的问题,用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.

解决者:

  • gem addressable gem in gemspecGemfile
gem 'addressable', '~> 2.7'
  • 需要addressable/uri

  • 适当添加。

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

【讨论】:

    猜你喜欢
    • 2019-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-05
    • 2016-12-25
    • 2021-02-04
    • 1970-01-01
    相关资源
    最近更新 更多