Skip to content

Instantly share code, notes, and snippets.

@seejohnrun
Created February 13, 2011 02:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seejohnrun/824374 to your computer and use it in GitHub Desktop.
Save seejohnrun/824374 to your computer and use it in GitHub Desktop.
Local short urls to avoid a short_urls table
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