Created
February 13, 2011 02:44
-
-
Save seejohnrun/824374 to your computer and use it in GitHub Desktop.
Local short urls to avoid a short_urls table
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
class ShortId | |
# We cut out vowels to avoid shortened strings from mistakenly | |
# forming words | |
Alphabet = 'bcdfghjklmnpqrstvwxyz0123456789BCDFGHJKLMNPQRSTVWXYZ' | |
AlphabetLength = Alphabet.length | |
# Encode a numeric ID | |
def self.encode(id) | |
alpha = '' | |
while id != 0 | |
alpha = Alphabet[id % AlphabetLength].chr + alpha | |
id /= AlphabetLength | |
end | |
alpha | |
end | |
# Decode an ID created with self.encode | |
def self.decode(alpha) | |
alpha = alpha.dup; id = 0 | |
0.upto(alpha.length - 1) do |i| | |
id += Alphabet.index(alpha[-1]) * (AlphabetLength ** i) | |
alpha.chop! | |
end | |
id | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment