Module: Philiprehberger::IdGen::Nanoid

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

Constant Summary collapse

DEFAULT_ALPHABET =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-'

Class Method Summary collapse

Class Method Details

.generate(size = 21, alphabet: DEFAULT_ALPHABET) ⇒ Object

Raises:



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

def generate(size = 21, alphabet: DEFAULT_ALPHABET)
  raise Error, 'Size must be positive' unless size.positive?
  raise Error, 'Alphabet must not be empty' if alphabet.empty?
  raise Error, 'Alphabet must be 256 characters or fewer' if alphabet.length > 256

  mask = ((1 << Math.log2(alphabet.length - 1).ceil) - 1) | 1
  step = (1.6 * mask * size / alphabet.length).ceil

  id = +''
  loop do
    bytes = SecureRandom.random_bytes(step)
    bytes.each_byte do |byte|
      index = byte & mask
      next if index >= alphabet.length

      id << alphabet[index]
      return id if id.length == size
    end
  end
end