Class: EncodedId::Encoders::Sqids

Inherits:
Object
  • Object
show all
Defined in:
lib/encoded_id/encoders/sqids.rb

Overview

Encoder implementation using the Sqids algorithm for encoding/decoding IDs.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(min_hash_length = 0, alphabet = Alphabet.alphanum, blocklist = Blocklist.empty, blocklist_mode = :length_threshold, blocklist_max_length = 32) ⇒ Sqids

Returns a new instance of Sqids.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/encoded_id/encoders/sqids.rb', line 14

def initialize(min_hash_length = 0, alphabet = Alphabet.alphanum, blocklist = Blocklist.empty, blocklist_mode = :length_threshold, blocklist_max_length = 32)
  @min_hash_length = min_hash_length
  @alphabet = alphabet
  @blocklist = blocklist
  @blocklist_mode = blocklist_mode
  @blocklist_max_length = blocklist_max_length

  @sqids = ::SqidsWithBlocklistMode.new(
    {
      min_length: min_hash_length,
      alphabet: alphabet.characters,
      blocklist: blocklist,
      blocklist_mode: blocklist_mode,
      blocklist_max_length: blocklist_max_length
    }
  )
rescue TypeError, ArgumentError => error
  raise InvalidInputError, "unable to create sqids instance: #{error.message}"
end

Instance Attribute Details

#alphabetObject (readonly)

: Alphabet



35
36
37
# File 'lib/encoded_id/encoders/sqids.rb', line 35

def alphabet
  @alphabet
end

#blocklistObject (readonly)

: Blocklist



36
37
38
# File 'lib/encoded_id/encoders/sqids.rb', line 36

def blocklist
  @blocklist
end

#min_hash_lengthObject (readonly)

: Integer



34
35
36
# File 'lib/encoded_id/encoders/sqids.rb', line 34

def min_hash_length
  @min_hash_length
end

Instance Method Details

#decode(hash) ⇒ Object



47
48
49
50
51
52
53
# File 'lib/encoded_id/encoders/sqids.rb', line 47

def decode(hash)
  return [] if hash.nil? || hash.empty?

  @sqids.decode(hash)
rescue
  raise InvalidInputError, "unable to unhash"
end

#encode(numbers) ⇒ Object



39
40
41
42
43
44
# File 'lib/encoded_id/encoders/sqids.rb', line 39

def encode(numbers)
  numbers.all? { Integer(_1) } # raises if conversion fails
  return "" if numbers.empty? || numbers.any?(&:negative?)

  @sqids.encode(numbers)
end