Sha256: a2cac5b41ee973fa6e24327d54b2128defea3316f6759582c137629c8c0c410d

Contents?: true

Size: 699 Bytes

Versions: 1

Compression:

Stored size: 699 Bytes

Contents

module PrefixedIds
  class PrefixId
    attr_reader :hashids, :model, :prefix

    def initialize(model, prefix, minimum_length: PrefixedIds.minimum_length, alphabet: PrefixedIds.alphabet, **options)
      @alphabet = alphabet
      @model = model
      @prefix = prefix.to_s
      @hashids = Hashids.new(model.table_name, minimum_length)
    end

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

    # decode returns an array
    def decode(id, fallback: false)
      fallback_value = fallback ? id : nil
      _, id_without_prefix = PrefixedIds.split_id(id)
      decoded_id = @hashids.decode(id_without_prefix).last
      decoded_id || fallback_value
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
prefixed_ids-1.2.0 lib/prefixed_ids/prefix_id.rb