-
-
Save tomlobato/e932818fa7eb989e645f2e64645cf7a5 to your computer and use it in GitHub Desktop.
Represents an UUID in a shorter and still URL compatible string (from 36 to 22 chars)
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
class UUIDShortner | |
IGNORE = '-' | |
BASE6_SLAB = ' ' * 22 | |
# 64 (6 bits) items dictionary | |
DICT = 'a'.upto('z').to_a + | |
'A'.upto('Z').to_a + | |
'0'.upto('9').to_a + | |
['_', '-'] | |
def self.uuid_to_base6 uuid | |
uuid_bits = 0 | |
uuid.each_char do |c| | |
next if c == IGNORE | |
uuid_bits = (uuid_bits << 4) | c.hex | |
end | |
base6 = BASE6_SLAB.dup | |
base6.size.times { |i| | |
base6[i] = DICT[uuid_bits & 0b111111] | |
uuid_bits >>= 6 | |
} | |
base6 | |
end | |
end | |
# Examples: | |
require 'securerandom' | |
uuid = ARGV[0] || SecureRandom.uuid | |
short = UUIDShortner.uuid_to_base6 uuid | |
puts "#{uuid}\n#{short}" | |
# ruby uuid_to_base6.rb | |
# c7e6a9e5-1fc6-4d5a-b889-4734e42b9ecc | |
# m75kKtZrjIRwnz8hLNQ5hd | |
# ruby uuid_to_base6.rb | |
# 6107f0c3-e980-4d66-9190-b9f1b9af2622 | |
# IyYR5gFUqgPznby6dd-bHb | |
# ruby uuid_to_base6.rb | |
# 94e66cad-3f12-45f3-982d-73dbfbb88da3 | |
# J2iU7V9CTG58fjXpTYM5uc |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment