Module: Philiprehberger::IdGen::Hashid

Defined in:
lib/philiprehberger/id_gen/hashid.rb

Constant Summary collapse

ALPHABET =
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'

Class Method Summary collapse

Class Method Details

.decode(string, salt: '') ⇒ Object

Raises:



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

def decode(string, salt: '')
  raise Error, 'String must not be empty' if string.nil? || string.empty?

  shuffled = shuffle_alphabet(ALPHABET, salt)
  base = shuffled.length

  string.each_char.reduce(0) do |acc, char|
    index = shuffled.index(char)
    raise Error, "Invalid character '#{char}'" unless index

    (acc * base) + index
  end
end

.encode(integer, salt: '', min_length: 8) ⇒ Object

Raises:



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/philiprehberger/id_gen/hashid.rb', line 12

def encode(integer, salt: '', min_length: 8)
  raise Error, 'Value must be a non-negative integer' unless integer.is_a?(Integer) && integer >= 0

  shuffled = shuffle_alphabet(ALPHABET, salt)
  base = shuffled.length

  result = +''
  value = integer + 1 # offset to avoid zero-length for 0
  while value.positive?
    result.prepend(shuffled[value % base])
    value /= base
  end

  # Pad to min_length using deterministic characters
  while result.length < min_length
    pad_char = shuffled[(integer + result.length) % base]
    result.prepend(pad_char)
  end

  result
end