Create a gist now

Instantly share code, notes, and snippets.

Obfuscated ids
module Base62
BASE_CHARS = '0SKVnQFHhGs9qo7p8cRW54duMYNXTCErx2tDmwO3kabfUB1elLvjiIgyJAZ6Pz'.split('')
BASE = BASE_CHARS.length
BASE_ENCODED_MIN_LENGTH = 1
def self.decode(number)
# assure string
number = number.to_s.reverse.split('')
decoded = 0
digits = number.length
# decode
digits.times do |i|
decoded+= BASE_CHARS.index(number[i]) * BASE**i
end
decoded
end
def self.encode(number)
if number.nil?
return nil
end
# assure numerical
number = number.to_i(10) unless number.is_a? Integer
encoded = ''
digits = (number > 0) ? 1 + (Math.log(number)/Math.log(BASE)).to_i : 0
# fill with leading zeros
(BASE_ENCODED_MIN_LENGTH - digits).times do
encoded << BASE_CHARS[0]
end
# convert the number
digits.times do |i|
divider = BASE**(digits - 1 - i)
encoded << BASE_CHARS[(number / divider).to_i]
number = number % divider
end
encoded
end
end
# extend Integer and String
class Integer
def to_base62
Base62.encode self
end
def from_base62
Base62.decode self
end
end
class String
def to_base62
Base62.encode self
end
def from_base62
Base62.decode self
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment