Quick, local short_urls
Cross-posted from http://engineering.patch.com/quick-local-shorturls
On patch.com, we generate short_urls for our editors to use on services like Twitter. The benefit of generating the short URL internally is three-fold:
- We get to maintain the Patch branding
- We don’t have to rely on an external shortening service
- We can be in control of how our links are created
The last one is really fun, because it means that we can cleverly name our short_urls in a way that they don’t need to make an extra request to the database for lookup. So, instead of a user requesting http://patch.com/bE582, and us looking up in a table what page that references, we can created a short URL like: http://patch.com/L-dbrB and serve the user Listing 281923.
Its really simple, as is the code to support it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | # John Crepezzi April 22, 2010 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 |
Enjoy!