Skip to content

Instantly share code, notes, and snippets.

@robhurring
Created September 15, 2010 20:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save robhurring/581399 to your computer and use it in GitHub Desktop.
Save robhurring/581399 to your computer and use it in GitHub Desktop.
# 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