Module: QuickShort::ShortId

Defined in:
lib/quick_short/short_id.rb

Overview

This module handles the actual encoding and decoding of the IDs

Constant Summary collapse

DefaultAlphabet =

This is the sequence of characters we use to encode the ID Note: We cut out vowels to avoid shortened strings from mistakenly forming words

'bcdfghjklmnpqrstvwxyz0123456789BCDFGHJKLMNPQRSTVWXYZ'

Class Method Summary collapse

Class Method Details

.alphabetObject

Get the alphabet to use



15
16
17
# File 'lib/quick_short/short_id.rb', line 15

def alphabet
  @alphabet ||= DefaultAlphabet
end

.decode(alpha) ⇒ Fixnum

Decode an ID created with encode

Parameters:

  • the (String)

    ID to decode

Returns:

  • (Fixnum)

    the decoded ID



34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/quick_short/short_id.rb', line 34

def decode(alpha)
  alpha = alpha.dup; id = 0
  0.upto(alpha.length - 1) do |i|
    letter = alpha[alpha.length - 1]
    alphabet_index = alphabet.index letter
    unless alphabet_index # bad character present?
      raise ArgumentError.new("Character not in Alphabet: #{letter}")
    end
    id += alphabet_index * (alphabet.length ** i)
    alpha.chop!
  end
  id
end

.encode(id) ⇒ String

Encode a numeric ID

Parameters:

  • id (Fixnum)
    • the ID to encode

Returns:

  • (String)

    the encoded ID



22
23
24
25
26
27
28
29
# File 'lib/quick_short/short_id.rb', line 22

def encode(id)
  alpha = ''
  while id != 0
    alpha = alphabet[id % alphabet.length].chr + alpha
    id /= alphabet.length
  end
  alpha
end