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.

asked Aug 29, 2012 at 0:35
\$\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"
Jeff Mercado
5,40229 silver badges33 bronze badges
answered Sep 2, 2012 at 0:37
\$\endgroup\$
2
  • \$\begingroup\$ URI.encode does not encode & as %26. \$\endgroup\$ Commented Sep 2, 2012 at 7:56
  • \$\begingroup\$ Correct, I meant CGI.escape(). I should review my review next time \$\endgroup\$ Commented Sep 3, 2012 at 4:02

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.