Class: PrefixedIds::PrefixId

Inherits:
Object
  • Object
show all
Defined in:
lib/prefixed_ids/prefix_id.rb

Constant Summary collapse

TOKEN =
123

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model, prefix, salt: PrefixedIds.salt, minimum_length: PrefixedIds.minimum_length, alphabet: PrefixedIds.alphabet, delimiter: PrefixedIds.delimiter, **options) ⇒ PrefixId

Returns a new instance of PrefixId.



7
8
9
10
11
# File 'lib/prefixed_ids/prefix_id.rb', line 7

def initialize(model, prefix, salt: PrefixedIds.salt, minimum_length: PrefixedIds.minimum_length, alphabet: PrefixedIds.alphabet, delimiter: PrefixedIds.delimiter, **options)
  @prefix = prefix.to_s
  @delimiter = delimiter.to_s
  @hashids = Hashids.new("#{model.table_name}#{salt}", minimum_length, alphabet)
end

Instance Attribute Details

#hashidsObject (readonly)

Returns the value of attribute hashids.



3
4
5
# File 'lib/prefixed_ids/prefix_id.rb', line 3

def hashids
  @hashids
end

#prefixObject (readonly)

Returns the value of attribute prefix.



3
4
5
# File 'lib/prefixed_ids/prefix_id.rb', line 3

def prefix
  @prefix
end

Instance Method Details

#decode(id, fallback: false) ⇒ Object

decode returns an array



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/prefixed_ids/prefix_id.rb', line 20

def decode(id, fallback: false)
  fallback_value = fallback ? id : nil
  _, id_without_prefix = PrefixedIds.split_id(id, @delimiter)
  decoded_hashid = @hashids.decode(id_without_prefix)

  if !valid?(decoded_hashid)
    fallback_value
  else
    _, *ids = decoded_hashid
    (ids.size == 1) ? ids.first : ids
  end
end

#encode(id) ⇒ Object



13
14
15
16
17
# File 'lib/prefixed_ids/prefix_id.rb', line 13

def encode(id)
  return if id.nil?

  @prefix + @delimiter + @hashids.encode([TOKEN] + Array.wrap(id))
end