module UrlShortener
class << self
CODESET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
BASE = CODESET.length # 62
def encode(id)
hash = ''
while id > 0
hash = CODESET[id % BASE].chr + hash
id = (id.to_f / BASE.to_f).floor
end
hash
end
def decode(hash)
id = 0
hash.chars.each_with_index do |c,i|
n = CODESET.index(c)
return if n < 0 # invalid codeset
id += n * (BASE ** (hash.length-i-1))
end
id
end
end
end
__END__
Usage:
Normally a web resource is referenced by a unique integer as in: http://site.com/posts/300.
The methods above simply encode the integer to base 62 with the codeset defined above.
It's the same thing as converting base 10 to base 16 (hex), but in this case we're converting
base 10 to our own base 62.
UrlShortener.encode(300)
=> "4Q"
UrlShortener.decode("4Q")
=> 300
UrlShortener.encode(1000000)
=> "4c92"