Class: PrettyId::SecRandom

Inherits:
Object
  • Object
show all
Defined in:
lib/pretty_id/sec_random.rb

Overview

taken from Ruby 2.5 implementation

Constant Summary collapse

ALPHANUMERIC =
[*'A'..'Z', *'a'..'z', *'0'..'9']

Class Method Summary collapse

Class Method Details

.alphanumeric(n = nil) ⇒ Object



8
9
10
11
# File 'lib/pretty_id/sec_random.rb', line 8

def self.alphanumeric(n=nil)
  n = 16 if n.nil?
  choose(ALPHANUMERIC, n)
end

.choose(source, n) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/pretty_id/sec_random.rb', line 13

def self.choose(source, n)
  size = source.size
  m = 1
  limit = size
  while limit * size <= 0x100000000
    limit *= size
    m += 1
  end
  result = ''.dup
  while m <= n
    rs = SecureRandom.random_number(limit)
    is = rs.digits(size)
    (m-is.length).times { is << 0 }
    result << source.values_at(*is).join('')
    n -= m
  end
  if 0 < n
    rs = SecureRandom.random_number(limit)
    is = rs.digits(size)
    if is.length < n
      (n-is.length).times { is << 0 }
    else
      is.pop while n < is.length
    end
    result.concat source.values_at(*is).join('')
  end
  result
end