shankardevy
shankardevy

Reputation: 4370

automatically URI decoding as needed

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.

Upvotes: 3

Views: 17836

Answers (3)

Teebs
Teebs

Reputation: 795

This works for me:

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

Upvotes: -2

Sahil Dhankhar
Sahil Dhankhar

Reputation: 3656

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?

Upvotes: 13

Nikita Chernov
Nikita Chernov

Reputation: 2061

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.

Upvotes: 2

Related Questions