3
a = 'some string'
b = URI.encode(a) # returns 'some%20string'
c = URI.encode(b) # returns 'some%2520string'

is there a way in ruby by which I can decode 'c' that gets me to 'a' string without decoding twice. My point is that I have some string that are encoded twice and some other that are encoded once. I want a method to automatically decode to normal string automatically identifying the number of time decoded.

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
shankardevy
  • 4,290
  • 5
  • 32
  • 49

3 Answers3

13

I guess the only way to achieve this is to keep decoding till it stop making changes. My facvourite for this kind of stuff is do while loop:

decoded = encoded
begin
  decoded = URI.decode(decoded) 
end while(decoded != URI.decode(decoded)  )

IMHO what you are looking for does not exist.

******** EDIT *************

Answers of another duplicate question for this on stackoverflow also suggests the same How to find out if string has already been URL encoded?

Community
  • 1
  • 1
Sahil Dhankhar
  • 3,596
  • 2
  • 31
  • 44
2

I can't find autodetection in docs, but its possible to implement this the following way with one extra #decode call:

def decode_uri(uri)
  current_uri, uri = uri, URI.decode(uri) until uri == current_uri
  uri
end

which will call #decode on uri until it will stop making any changes to it.

Nikita Chernov
  • 2,031
  • 16
  • 13
-2

This works for me:

def decode_uri(encoded)
  decoded = encoded
  begin
    decoded = URI.decode(decoded)
  end while(decoded != URI.decode(decoded))
  return decoded
end
Teebu
  • 677
  • 7
  • 18