Last active
August 29, 2015 14:04
-
-
Save SkyM/4bb0d3f049584b572028 to your computer and use it in GitHub Desktop.
Short Code Generator
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
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