Sha256: bb09c2c5d76d1d04ec2aabe0953fc41543ebd77eb71b8dde962852d724838391
Contents?: true
Size: 1.37 KB
Versions: 9
Compression:
Stored size: 1.37 KB
Contents
module Hippo::Concerns # @see ClassMethods module RandomIdentifer extend ActiveSupport::Concern # ### Random Identifier Concern # This adds the {#has_random_hash_code} class method module ClassMethods # A random string that identifies an model # The code is generated by {Hippo::Strings.random} for new records # It's useful for generating links for anonymous access to an entity that cannot be guessed. # @param field_name [Symbol] which field should the hash_code be stored in # @param length [Integer] how long the hash_code should be def has_random_identifier(field_name: :identifier, length: 12) validates field_name, presence: { message: "random identifier is not set (should be automatically chosen)" } before_validation(on: :create) do 5.times do if self[field_name].blank? code = Hippo::Strings.random(length) self[field_name] = code if self.class.where("#{field_name}" => code).none? end break if self[field_name].present? end end end end end end
Version data entries
9 entries across 9 versions & 1 rubygems