Class: PrefixedIds::PrefixId
- Inherits:
-
Object
- Object
- PrefixedIds::PrefixId
- Defined in:
- lib/prefixed_ids/prefix_id.rb
Constant Summary collapse
- TOKEN =
123
Instance Attribute Summary collapse
-
#hashids ⇒ Object
readonly
Returns the value of attribute hashids.
-
#prefix ⇒ Object
readonly
Returns the value of attribute prefix.
Instance Method Summary collapse
-
#decode(id, fallback: false) ⇒ Object
decode returns an array.
- #encode(id) ⇒ Object
-
#initialize(model, prefix, salt: PrefixedIds.salt, minimum_length: PrefixedIds.minimum_length, alphabet: PrefixedIds.alphabet, delimiter: PrefixedIds.delimiter, **options) ⇒ PrefixId
constructor
A new instance of PrefixId.
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, **) @prefix = prefix.to_s @delimiter = delimiter.to_s @hashids = Hashids.new("#{model.table_name}#{salt}", minimum_length, alphabet) end |
Instance Attribute Details
#hashids ⇒ Object (readonly)
Returns the value of attribute hashids.
3 4 5 |
# File 'lib/prefixed_ids/prefix_id.rb', line 3 def hashids @hashids end |
#prefix ⇒ Object (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 26 27 |
# 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) if fallback && !valid?(decoded_hashid) fallback_value else decoded_hashid.last end 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 |