Class: EncodedId::Encoders::Sqids
- Inherits:
-
Object
- Object
- EncodedId::Encoders::Sqids
- Defined in:
- lib/encoded_id/encoders/sqids.rb
Overview
Encoder implementation using the Sqids algorithm for encoding/decoding IDs.
Instance Attribute Summary collapse
-
#alphabet ⇒ Object
readonly
: Alphabet.
-
#blocklist ⇒ Object
readonly
: Blocklist.
-
#min_hash_length ⇒ Object
readonly
: Integer.
Instance Method Summary collapse
- #decode(hash) ⇒ Object
- #encode(numbers) ⇒ Object
-
#initialize(min_hash_length = 0, alphabet = Alphabet.alphanum, blocklist = Blocklist.empty, blocklist_mode = :length_threshold, blocklist_max_length = 32) ⇒ Sqids
constructor
A new instance of Sqids.
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
#alphabet ⇒ Object (readonly)
: Alphabet
35 36 37 |
# File 'lib/encoded_id/encoders/sqids.rb', line 35 def alphabet @alphabet end |
#blocklist ⇒ Object (readonly)
: Blocklist
36 37 38 |
# File 'lib/encoded_id/encoders/sqids.rb', line 36 def blocklist @blocklist end |
#min_hash_length ⇒ Object (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 |