Sha256: c160ff890e8e98eccc95e36d56d4b6b334b80753aee17b15cd2368394a77e98c

Contents?: true

Size: 1.02 KB

Versions: 1

Compression:

Stored size: 1.02 KB

Contents

require "prefixed_ids/version"
require "prefixed_ids/engine"

module PrefixedIds
  MINIMUM_TOKEN_LENGTH = 24

  class MinimumLengthError < StandardError; end

  module Attribute
    extend ActiveSupport::Concern

    module ClassMethods
      def has_prefix_id(prefix, attribute: :prefix_id, length: MINIMUM_TOKEN_LENGTH)
        if length < MINIMUM_TOKEN_LENGTH
          raise MinimumLengthError, "Token requires a minimum length of #{MINIMUM_TOKEN_LENGTH} characters."
        end

        # Load securerandom only when has_secure_token is used.
        require "active_support/core_ext/securerandom"
        define_method("regenerate_#{attribute}") { update! attribute => self.class.generate_unique_prefix_id(prefix, length: length) }
        before_create { send("#{attribute}=", self.class.generate_unique_prefix_id(prefix, length: length)) unless send("#{attribute}?") }
      end

      def generate_unique_prefix_id(prefix, length: MINIMUM_TOKEN_LENGTH)
        prefix.to_s + "_" + SecureRandom.base58(length)
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
prefixed_ids-1.0.1 lib/prefixed_ids.rb