Last active
December 15, 2015 14:09
-
-
Save grauwoelfchen/5272316 to your computer and use it in GitHub Desktop.
Encode / Decode URL UTF-8 String
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# encoding: utf-8 | |
require 'optparse' | |
require 'cgi' | |
VERSION = '0.2' | |
def help | |
<<-MAN | |
usage: url [-ed] 'STR I N G' | |
-e, --encode encode text, default. | |
-d, --decode decode text. | |
-h, --help show this help. | |
MAN | |
end | |
action = 'encode' | |
parser = OptionParser.new | |
parser.on('-e', '--encode') { action = 'encode' } | |
parser.on('-d', '--decode') { action = 'decode' } | |
parser.on_tail('-h', '--help') { puts help; exit 0 } | |
args = ARGV.dup | |
begin | |
parser.parse!(args) | |
rescue StandardError | |
puts help | |
exit 1 | |
end | |
str = args.join(' ').strip | |
res = str.dup | |
if action == 'encode' | |
str.scan(/[^A-z\.\/\?\-:=&0-9]/).map do |char| | |
res.gsub!(char, CGI.escape(char)) | |
end | |
else | |
res = CGI.unescape(str) | |
end | |
unless str.empty? | |
puts res | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment