Skip to content

Instantly share code, notes, and snippets.

@SkyM
Last active August 29, 2015 14:04
Show Gist options
  • Save SkyM/4bb0d3f049584b572028 to your computer and use it in GitHub Desktop.
Save SkyM/4bb0d3f049584b572028 to your computer and use it in GitHub Desktop.
Short Code Generator
require "digest/md5"
module App
module Tools
class ShortCodeGenerator
attr_reader :max_code_length
def initialize(max_code_length)
if max_code_length < 2
raise "Code length needs to be a value of AT LEAST '2'!"
end
@max_code_length = max_code_length
end
def create(object_id)
url36 = Digest::MD5.hexdigest(object_id.to_s + SALT).slice(0..@max_code_length)
base62 = ['0'..'9','A'..'Z','a'..'z'].map{|a| a.to_a}.flatten
base36 = {};['0'..'9','a'..'z'].map{|range| range.to_a}.flatten.each_with_index{|char, position| base36[char] = position}
url62, url10 = "",0
# convert to base10
url36.reverse.chars.to_a.each_with_index { |c,i| url10 += base36[c] * (36 ** i)}
# convert to base62
@max_code_length.times{|i| url62 << base62[url10 % 62]; url10 = url10 / 62}
url62
end
private
SALT = "YeFrugehacuasdfasdfasdfuxu$-Faspawazasay*me$EcaruS?at@uwrejaw$nuz"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment