Class: TimeBasedUUID

Inherits:
Object
  • Object
show all
Defined in:
lib/callstacking/rails/time_based_uuid.rb

Constant Summary collapse

EPOCH_OFFSET =

A custom epoch, it could be the UNIX timestamp when the application was created (in milliseconds)

1468418800000
MAX_INT8_VALUE =
9223372036854775807

Class Method Summary collapse

Class Method Details

.generateObject



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/callstacking/rails/time_based_uuid.rb', line 7

def self.generate
  # Get the current time in milliseconds
  current_time = (Time.now.to_f * 1000).to_i

  # Subtract the custom epoch to reduce the timestamp size
  timestamp = current_time - EPOCH_OFFSET

  # Generate a random 64-bit number using SecureRandom
  random_bits = SecureRandom.random_number(1 << 64)

  # Combine the timestamp and the random bits
  uuid = (timestamp << 64) | random_bits

  # Ensure the UUID fits into a PostgreSQL int8 column
  uuid = uuid % MAX_INT8_VALUE if uuid > MAX_INT8_VALUE

  uuid
end