Sha256: f727ba2859e293ae11d1796f89a93502c405ecd5069a4d28e5a22a723a6284e7

Contents?: true

Size: 1.05 KB

Versions: 1

Compression:

Stored size: 1.05 KB

Contents

module PrefixedIds
  class PrefixId
    attr_reader :hashids, :prefix

    TOKEN = 123

    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

    def encode(id)
      return if id.nil?

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

    # decode returns an array
    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
        _, id, *composite = decoded_hashid
        composite.empty? ? id : composite
      end
    end

    private

    def valid?(decoded_hashid)
      decoded_hashid.size >= 2 && decoded_hashid.first == TOKEN
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

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