Skip to content

Instantly share code, notes, and snippets.

@ahsandar
Forked from psychocandy/URI-monkey-patch.rb
Created October 13, 2017 04:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahsandar/b5a3d82a66cb769fc76fd141e749a284 to your computer and use it in GitHub Desktop.
Save ahsandar/b5a3d82a66cb769fc76fd141e749a284 to your computer and use it in GitHub Desktop.
Fix ArgumentError invalid %-encoding for malformed URLs
# The following should prevent an ArgumentError "invalid %-encoding (...%)" exception from being raised for malformed URLs.
# To use this code simply drop this in your rails app initializers.
# See: https://github.com/rack/rack/issues/337
# Taken from: http://stackoverflow.com/a/11162317/1075006
module URI
major, minor, patch = RUBY_VERSION.split('.').map { |v| v.to_i }
if major == 1 && minor <= 9
def self.decode_www_form_component(str, enc=nil)
if TBLDECWWWCOMP_.empty?
tbl = {}
256.times do |i|
h, l = i>>4, i&15
tbl['%%%X%X' % [h, l]] = i.chr
tbl['%%%x%X' % [h, l]] = i.chr
tbl['%%%X%x' % [h, l]] = i.chr
tbl['%%%x%x' % [h, l]] = i.chr
end
tbl['+'] = ' '
begin
TBLDECWWWCOMP_.replace(tbl)
TBLDECWWWCOMP_.freeze
rescue
end
end
str = str.gsub(/%(?![0-9a-fA-F]{2})/, "%25")
str.gsub(/\+|%[0-9a-fA-F]{2}/) {|m| TBLDECWWWCOMP_[m]}
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment