Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Created August 29, 2018 04:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshCheek/c25b12ac3d188cfac4f5f480c02da19f to your computer and use it in GitHub Desktop.
Save JoshCheek/c25b12ac3d188cfac4f5f480c02da19f to your computer and use it in GitHub Desktop.
Encoding an integer id as a slug
# Note that I haven't read about the difference between the base 64 RFCs
def to_slug(id)
ber_id = [id].pack('w') # => "\x85\xC8_"
b64_id = [ber_id].pack('m') # => "hchf\n"
b64_id[/\A(.*?)=*\n*\z/, 1] # => "hchf"
end # => :to_slug
def from_slug(slug)
slug.unpack('m') # => ["\x85\xC8_"]
.first # => "\x85\xC8_"
.unpack('w') # => [91231]
.first # => 91231
end # => :from_slug
id = 91231 # => 91231
slug = to_slug id # => "hchf"
from_slug slug # => 91231
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment