5
\$\begingroup\$

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.

\$\endgroup\$
1

1 Answer 1

8
\$\begingroup\$

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"
\$\endgroup\$
2
  • \$\begingroup\$ URI.encode does not encode & as %26. \$\endgroup\$ Sep 2, 2012 at 7:56
  • \$\begingroup\$ Correct, I meant CGI.escape(). I should review my review next time \$\endgroup\$ Sep 3, 2012 at 4:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.