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
19
# 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
  @block_size = block_size
  @mask = (1 << block_size) - 1
  @mapping = (0..block_size - 1).to_a
end

Instance Method Details

#decode_url(n) ⇒ Object



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

def decode_url(n)
  decode(debase(n))
end

#encode_url(n, min_length: MIN_LENGTH) ⇒ Object



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

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