I have the following Ruby code snippet:
url = "http://somewiki.com/index.php?book=#{author}:#{title}&action=edit"
encoded = URI.encode(url)
encoded.gsub(/&/, "%26").sub(/%26action/, "&action")
The last line is needed since I have to encode the ampersands (&
) in the author and title but I need to leave the last one (&action...
) intact.
Consider this example for clarity:
author = "John & Diane"
title = "Our Life & Work"
url = "http://somewiki.com/index.php?book=#{author}:#{title}&action=edit"
encoded = URI.encode(url)
encoded.gsub(/&/, "%26").sub(/%26action/, "&action")
# => "http://somewiki.com/index.php?book=John%20%26%20Diane:Our%20Life%20%26%20Work&action=edit"
Although this result is satisfactory, I'd like to clean the original code with the gsub/sub
calls. Any ideas?
PS: I could "clean" both params before passing them to the url = ...
line but then the %
characters will be re-encoded as %25
by the URI.encode
call so I don't think that's an option. I'd love to be proved wrong here though.
-
\$\begingroup\$ See stackoverflow.com/a/36191180/520567 , you can use a specified parser. \$\endgroup\$akostadinov– akostadinov2021年03月08日 13:51:33 +00:00Commented Mar 8, 2021 at 13:51
1 Answer 1
Unless you need the unencoded url (for logging?), I would just:
encoded_url = "http://somewiki.com/index.php?book=#{CGI.escape(author)}:#{CGI.escape(title)}&action=edit"
-
\$\begingroup\$
URI.encode
does not encode & as %26. \$\endgroup\$Federico Builes– Federico Builes2012年09月02日 07:56:34 +00:00Commented Sep 2, 2012 at 7:56 -
\$\begingroup\$ Correct, I meant CGI.escape(). I should review my review next time \$\endgroup\$Wayne Walker– Wayne Walker2012年09月03日 04:02:26 +00:00Commented Sep 3, 2012 at 4:02