Class: Ruby::ShortUrl::Encoder

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby/short_url/encoder.rb

Overview

Original imprementation is here: github.com/Alir3z4/python-short_url

Constant Summary collapse

DEFAULT_ALPHABET =
((0..9).to_a + ('A'..'Z').to_a + ('a'..'z').to_a).join
DEFAULT_BLOCK_SIZE =
24
MIN_LENGTH =
5

Instance Method Summary collapse

Constructor Details

#initialize(alphabet: DEFAULT_ALPHABET, block_size: DEFAULT_BLOCK_SIZE) ⇒ Encoder

Returns a new instance of Encoder.

Raises:

  • (ArgumentError)


11
12
13
14
15
16
17
18
# File 'lib/ruby/short_url/encoder.rb', line 11

def initialize(alphabet: DEFAULT_ALPHABET, block_size: DEFAULT_BLOCK_SIZE)
  raise ArgumentError, 'alphabet must contain at least 2 characters.' if alphabet.length < 2
  raise ArgumentError, 'block_size must be greater than 0.' unless block_size > 0

  @alphabet = alphabet
  @mask = (1 << block_size) - 1
  @mapping = (0...block_size).to_a.reverse!
end

Instance Method Details

#decode_url(str) ⇒ Object



24
25
26
# File 'lib/ruby/short_url/encoder.rb', line 24

def decode_url(str)
  decode(debase(str))
end

#encode_url(int, min_length: MIN_LENGTH) ⇒ Object



20
21
22
# File 'lib/ruby/short_url/encoder.rb', line 20

def encode_url(int, min_length: MIN_LENGTH)
  enbase(encode(int), min_length)
end