Module: Seofy::Encoders::Base36

Defined in:
lib/seofy/encoders/base36.rb

Constant Summary collapse

THIRTY_SIX =
('0'..'9').to_a + ('a'..'z').to_a
LENGTH =
THIRTY_SIX.size

Class Method Summary collapse

Class Method Details

.decode(base36) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/seofy/encoders/base36.rb', line 20

def decode( base36 )
  s = base36.to_s.reverse.split('')

  total = 0
  s.each_with_index do |char, index|
    if ord = THIRTY_SIX.index(char)
      total += ord * (LENGTH ** index)
    else
      raise ArgumentError, "#{base36} has #{char} which is not valid"
    end
  end
  total.to_s
end

.encode(numeric) ⇒ Object

Raises:

  • (ArgumentError)


7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/seofy/encoders/base36.rb', line 7

def encode( numeric )
  raise ArgumentError unless Numeric === numeric

  return '0' if numeric == 0
  s = ''

  while numeric > 0
    s << Base36::THIRTY_SIX[numeric.modulo(LENGTH)]
    numeric /= LENGTH
  end
  s.reverse
end

.random(length) ⇒ Object



34
35
36
# File 'lib/seofy/encoders/base36.rb', line 34

def random(length) 
  Array.new(length) { THIRTY_SIX[rand(THIRTY_SIX.size - 1)] }.join
end