public
Last active

Obfuscated ids

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.