Created
September 15, 2010 20:18
-
-
Save robhurring/581399 to your computer and use it in GitHub Desktop.
URL shortening in ruby : http://proccli.com/url-shortening-ruby-rails
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
# You can use the model's ID (PK/Serial) to generate a token which can be reversed: | |
# Example: | |
# Url.find(7213).shortened #=> 5kd | |
# Url.find_by_shortened("5kd") #=> #<Url id: 7213...> | |
class Url < ActiveRecord::Base | |
Radix = 36 | |
# convert ID into a shortened version | |
def shortened | |
id.to_s(Radix) | |
end | |
# unconvert the shortened version back to an ID | |
def self.shortened_to_id(shortened) | |
shortened.to_i(Radix) | |
end | |
# convert and lookup | |
def self.find_by_shortened(shortened) | |
find shortened_to_id(shortened) | |
end | |
end |
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
# make tinyurl-ish tokens for pages so you dont have a goofy MD5 running amuck | |
# Example: | |
# make_token #=> "32uelywr" | |
# NOTE: the longer the number, the longer the token | |
def make_token | |
("%d%d" % [rand(100), Time.now.to_i]).to_i.to_s(36) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment