Search code examples
ruby

Ruby 2.7 says URI.escape is obsolete, what replaces it?


I'm using URI.encode to generate HTML data URLs:

visit "data:text/html,#{URI::encode(html)}"

After upgrading to Ruby 2.7.1, interpreter started warning:

warning: URI.escape is obsolete

Recommended replacements of this are CGI.escape and URI.encode_www_form_component. However, they're not doing same thing:

2.7.1 :007 > URI.escape '<html>this and that</html>'
(irb):7: warning: URI.escape is obsolete
 => "%3Chtml%3Ethis%20and%20that%3C/html%3E"
2.7.1 :008 > CGI.escape '<html>this and that</html>'
 => "%3Chtml%3Ethis+and+that%3C%2Fhtml%3E"
2.7.1 :009 > URI.encode_www_form_component '<html>this and that</html>'
 => "%3Chtml%3Ethis+and+that%3C%2Fhtml%3E"

Result of these slight encoding differences - html page where spaces are replaced by +. My question is - what's a good replacement of URI.encode for this use case?


Solution

  • There is no official RFC 3986-compliant URI escaper in the Ruby standard library today.

    See Why is URI.escape() marked as obsolete and where is this REGEXP::UNSAFE constant? for background.

    There are several methods that have various issues with them as you have discovered and pointed out in the comment:

    • They produce deprecation warnings
    • They do not claim standards compliance
    • They are not escaping in accordance with RFC 3986
    • They are implemented in tangentially related libraries