URL shortening in ruby : http://proccli.com/url-shortening-ruby-rails
# 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 |
# 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