Class: ShortUrlTokenGenerator

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

Class Method Summary collapse

Class Method Details

.base_notation(num, base = nil) ⇒ Object

Calculate base notation



31
32
33
34
# File 'lib/short_url_token_generator.rb', line 31

def self.base_notation num, base = nil
  base = mapping.length if base.nil?
  num < base ? "#{num}" : "#{base_notation (num/base).floor, base}-#{num % base}"
end

.decode(token) ⇒ Object

Decode token (for correct decoding, the token must be generated using this class) Param: token



20
21
22
23
24
25
26
27
28
# File 'lib/short_url_token_generator.rb', line 20

def self.decode token
  return -1 if token.length > 15
  num = i = 0
  token.chars.to_a.reverse_each do |t|
    num += mapping.index(t) * mapping.length**i unless mapping.index(t).nil?
    i += 1
  end
  num
end

.generate(num) ⇒ Object

Generate token (using alpha-numeric mapping) Param: num (index of the URL)



12
13
14
15
16
# File 'lib/short_url_token_generator.rb', line 12

def self.generate num
  token = ""
  base_notation(num).split('-').each { |position| token += "#{mapping[position.to_i]}" }
  token
end

.mappingObject

Get mapping



6
7
8
# File 'lib/short_url_token_generator.rb', line 6

def self.mapping
  @mapping.to_s.split //
end