Universally Unique Lexicographically Sortable Identifier implementation for Ruby
Universally Unique Lexicographically Sortable Identifier implementation for Ruby
Official specification page: https://github.com/ulid/spec
UUID can be suboptimal for many uses-cases because:
Instead, herein is proposed ULID:
gem install ulid
require 'ulid'
ULID.generate # 01ARZ3NDEKTSV4RRFFQ69G5FAV
I want to generate a ULID using an arbitrary timestamp
You can optionally pass a Time
instance to ULID.generate
to set an arbitrary timestamp component, i.e. the prefix of the ULID.
time_t1 = Time.now
ulid = ULID.generate(time_t1)
I want to generate a ULID using an arbitrary suffix, i.e. without the randomness component
You can optionally pass a 80-bit hex-encodable String
on the argument suffix
to ULID.generate
. This will replace the randomness component
by the suffix provided. This allows for fully deterministic ULIDs.
require 'securerandom'
time = Time.now
an_event_identifier = SecureRandom.uuid
ulid1 = ULID.generate(time, suffix: an_event_identifier)
ulid2 = ULID.generate(time, suffix: an_event_identifier)
ulid1 == ulid2 # true
Below is the current specification of ULID as implemented in this repository. Note: the binary format has not been implemented.
01AN4Z07BY 79KA1307SR9X4MV3
|----------| |----------------|
Timestamp Randomness
10 chars 16 chars
48bits 80bits
base32 base32
Timestamp
Randomness
The left-most character must be sorted first, and the right-most character sorted last. The default ASCII order is used for sorting.
The components are encoded as 16 octets. Each component is encoded with the Most Significant Byte first (network byte order).
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| 32_bit_uint_time_high |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| 16_bit_uint_time_low | 16_bit_uint_random |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| 32_bit_uint_random |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| 32_bit_uint_random |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
ttttttttttrrrrrrrrrrrrrrrr
where
t is Timestamp
r is Randomness
bundle exec rake test