Created
November 3, 2012 15:18
-
-
Save xdite/4007635 to your computer and use it in GitHub Desktop.
URL shortner
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
# -*- encoding : utf-8 -*- | |
require 'digest/md5' | |
module UrlShorter | |
ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".split(//) | |
def self.short!(url) | |
hex = Digest::MD5.hexdigest(url) | |
hexlen = hex.length | |
subhexlen = hexlen / 8 | |
output = [] | |
for i in 0..subhexlen-1 | |
subhex = hex[i*8,8] | |
int = 0x3FFFFFFF & ("0x#{subhex}".to_i(16)) | |
out = "" | |
for j in 0..5 | |
val = 0x0000001F & int | |
int = int >> 5 | |
out += ALPHABET[val] | |
end | |
output << out | |
end | |
return output[0] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment