Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 814
shankardevy Avatar asked Dec 07 '25 03:12

shankardevy


2 Answers

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?

like image 122
Sahil Dhankhar Avatar answered Dec 08 '25 17:12

Sahil Dhankhar


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.

like image 28
Nikita Chernov Avatar answered Dec 08 '25 17:12

Nikita Chernov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!