Skip to content

Instantly share code, notes, and snippets.

@bjeanes
Last active June 5, 2020 00:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjeanes/e75120fd6c44a3040a033a3dee0f8d00 to your computer and use it in GitHub Desktop.
Save bjeanes/e75120fd6c44a3040a033a3dee0f8d00 to your computer and use it in GitHub Desktop.
Compact URL-safe UUID representation. It might almost be worth having a base66 version (there are 66 url-safe chars)
require 'securerandom'
require 'base64'
module UUID64
extend self
def generate
encode SecureRandom.uuid
end
def encode(uuid)
bytes = uuid.downcase.scan(/[0-9a-f]{4}/).map { |x| x.to_i(16) }
Base64.urlsafe_encode64(bytes.pack('n*')).delete('=')
end
def decode(string)
string = string.gsub(/(==)?$/, '==') # re-pad, if necessary
bytes = Base64.urlsafe_decode64(string).unpack('NnnnnN')
"%08x-%04x-%04x-%04x-%04x%08x" % bytes
end
end
@bjeanes
Copy link
Author

bjeanes commented Dec 19, 2016

e.g.

> 10.times.each { u = SecureRandom.uuid; puts "#{u}:\t#{UUID64.encode(u)}" }
397854dd-cf74-4b34-a533-e3ff9ce757f8:	OXhU3c90SzSlM-P_nOdX-A
a59b6779-3cd0-418a-9143-7870a0be9608:	pZtneTzQQYqRQ3hwoL6WCA
04eea16d-4f50-4a81-ab5d-e8a96b734c0c:	BO6hbU9QSoGrXeipa3NMDA
f7b42cd7-573c-4898-a335-b71965d242a2:	97Qs11c8SJijNbcZZdJCog
28221298-11c0-4062-86aa-a935eb9f4bb9:	KCISmBHAQGKGqqk1659LuQ
a46a050f-3966-4f16-9a88-08b6b06e0955:	pGoFDzlmTxaaiAi2sG4JVQ
998219fb-428f-4494-90df-94d6b719f07b:	mYIZ-0KPRJSQ35TWtxnwew
ed3ccf27-9afa-4837-9f17-984a16cd868f:	7TzPJ5r6SDefF5hKFs2Gjw
683dd05d-9ef5-46f9-a41a-440b1073302d:	aD3QXZ71RvmkGkQLEHMwLQ
07ad32c4-94ec-4ffd-a1fe-dc247fcdae51:	B60yxJTsT_2h_twkf82uUQ

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment