Class: Tins::Token

Inherits:
String show all
Defined in:
lib/tins/token.rb

Constant Summary collapse

DEFAULT_ALPHABET =
((?0..?9).to_a + (?a..?z).to_a + (?A..?Z).to_a).freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Token

def initialize(bits: 128, length: nil, alphabet: DEFAULT_ALPHABET)



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/tins/token.rb', line 6

def initialize(options = {})
  bits     = options[:bits] || 128
  length   = options[:length]
  alphabet = options[:alphabet] || DEFAULT_ALPHABET
  alphabet.size > 1 or raise ArgumentError, 'need at least 2 symbols in alphabet'
  if length
    length > 0 or raise ArgumentError, 'length has to be positive'
  else
    bits > 0 or raise ArgumentError, 'bits has to be positive'
    length = (Math.log(1 << bits) / Math.log(alphabet.size)).ceil
  end
  self.bits = (Math.log(alphabet.size ** length) / Math.log(2)).floor
  token = ''
  length.times { token << alphabet[rand(alphabet.size)] }
  super token
end

Instance Attribute Details

#bitsObject

Returns the value of attribute bits.



23
24
25
# File 'lib/tins/token.rb', line 23

def bits
  @bits
end