Class: Wee::IdGenerator::Secure

Inherits:
Wee::IdGenerator show all
Defined in:
lib/wee/id_generator.rb

Overview

Returned ids are unique with a very high probability and it’s very hard to guess the next or any used id.

Instance Method Summary collapse

Constructor Details

#initialize(salt = 'wee') ⇒ Secure

Returns a new instance of Secure.



39
40
41
# File 'lib/wee/id_generator.rb', line 39

def initialize(salt='wee')
  @salt = salt
end

Instance Method Details

#nextObject



60
61
62
63
64
65
66
# File 'lib/wee/id_generator.rb', line 60

def next
  str = defined?(::SecureRandom) ? next_secure : next_md5
  packed = [str].pack('m')
  packed.tr!("=\r\n", '')
  packed.tr!('+/', '-_')
  packed
end

#next_md5Object



43
44
45
46
47
48
49
50
51
52
# File 'lib/wee/id_generator.rb', line 43

def next_md5
  now = Time.now
  dig = Digest::MD5.new
  dig.update(now.to_s)
  dig.update(now.usec.to_s)
  dig.update(rand(0).to_s)
  dig.update($$.to_s)
  dig.update(@salt.to_s)
  dig.digest
end

#next_secureObject



54
55
56
57
58
# File 'lib/wee/id_generator.rb', line 54

def next_secure
  SecureRandom.random_bytes(16)
rescue NotImplementedError
  next_md5
end