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, 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, 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, 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


18
19
20
21
22
23
24
25
# File 'lib/prefixed_ids/prefix_id.rb', line 18

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)
  return fallback_value unless valid?(decoded_hashid)

  decoded_hashid.last || fallback_value
end

#encode(id) ⇒ Object


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

def encode(id)
  @prefix + @delimiter + @hashids.encode(TOKEN, id)
end