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.



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

def initialize(alphabet: DEFAULT_ALPHABET, block_size: DEFAULT_BLOCK_SIZE)
  raise ArgumentError.new 'alphabet must contain at least 2 characters.' if alphabet.length < 2
  raise ArgumentError.new '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



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

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

#encode_url(n, min_length: MIN_LENGTH) ⇒ Object



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

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