Module: Philiprehberger::IdGen::Cuid2

Defined in:
lib/philiprehberger/id_gen/cuid2.rb

Constant Summary collapse

DEFAULT_LENGTH =
24
ALPHABET =
'abcdefghijklmnopqrstuvwxyz'

Class Method Summary collapse

Class Method Details

.generate(length = DEFAULT_LENGTH) ⇒ Object

Raises:



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/philiprehberger/id_gen/cuid2.rb', line 14

def generate(length = DEFAULT_LENGTH)
  raise Error, 'Length must be between 2 and 32' unless length.between?(2, 32)

  timestamp = Time.now.to_f.to_s
  random = SecureRandom.hex(32)
  counter_value = counter
  entropy = "#{timestamp}#{random}#{counter_value}"
  hash = Digest::SHA256.hexdigest(entropy)

  # First char is always a letter (for safe use as identifiers)
  first_char = ALPHABET[SecureRandom.random_number(ALPHABET.length)]
  # Remaining chars from the hash, converted to base36
  body = hash.to_i(16).to_s(36)

  result = first_char + body
  result[0, length]
end