Created
August 29, 2018 04:45
-
-
Save JoshCheek/c25b12ac3d188cfac4f5f480c02da19f to your computer and use it in GitHub Desktop.
Encoding an integer id as a slug
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
# 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