HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Encoding special characters in URLs with Ruby

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withrubyspecialencodingcharactersurls

Problem

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.

Solution

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"

Code Snippets

encoded_url = "http://somewiki.com/index.php?book=#{CGI.escape(author)}:#{CGI.escape(title)}&action=edit"

Context

StackExchange Code Review Q#15165, answer score: 8

Revisions (0)

No revisions yet.