automatically URI decoding as needed

15,396

Solution 1

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?

Solution 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.

Share:
15,396
shankardevy
Author by

shankardevy

Updated on June 04, 2022

Comments

  • shankardevy
    shankardevy almost 2 years
    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.