1

I am using URI.encode to encode url's in my rail's application. But sometimes these url's can be already encoded and I do not want to encode them again. I can see one solution here: How to find out if string has already been URL encoded?

However, was wondering is there any API already available in ruby for doing this ?

Also as suggested in https://stackoverflow.com/a/2295286/1475737 is decoding the string and checking its length with original a correct solution ?

Appreciate any suggestions!

Community
  • 1
  • 1
snow_leopard
  • 1,466
  • 2
  • 20
  • 36

1 Answers1

0

The 'uri' module has a regular expression holding the list of characters which should be escaped for URI encoding:

require 'uri'

URI::REGEXP::UNSAFE

=> /[^-_.!~*'()a-zA-Z\d;\/?:@&=+$,\[\]]/n

So one solution is to test whether the given string matches this regexp and encode it only if does.

nimrodm
  • 23,081
  • 7
  • 58
  • 59
  • This does not seem to be defined for ruby 1.9.3 :(. – snow_leopard Dec 16 '14 at 13:15
  • True. In fact, 'uri.encode' has been deprecated and the 'cgi' module should be used instead. Sadly, CGI does not provide a similar constant. – nimrodm Dec 16 '14 at 13:37
  • Also, This was suggested here as well http://stackoverflow.com/a/2295317/1475737 but its have a non-working example as well. – snow_leopard Dec 16 '14 at 13:39
  • 1
    This has been rebuild in 1.9.3 You can try the following: ***URI::Parser.new.pattern*** but not sure if this returns what you want.... – codingbunny Dec 16 '14 at 13:55