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 = ALPHABET[SecureRandom.random_number(ALPHABET.length)]
body = hash.to_i(16).to_s(36)
result = first_char + body
result[0, length]
end
|