Sha256: 75de8ace1a693f27a24b2f54049e2fcfe22ac1c28c9a4eb1afb0228852e53b53

Contents?: true

Size: 691 Bytes

Versions: 3

Compression:

Stored size: 691 Bytes

Contents

module Federails
  module HasUuid
    extend ActiveSupport::Concern

    included do
      before_validation :generate_uuid
      validates :uuid, presence: true, uniqueness: true

      def self.find_param(param)
        find_by!(uuid: param)
      end
    end

    def to_param
      uuid
    end

    # Override UUID accessor to provide lazy initialization of UUIDs for old data
    def uuid
      if self[:uuid].blank?
        generate_uuid
        save!
      end
      self[:uuid]
    end

    private

    def generate_uuid
      return if self[:uuid].present?

      (self.uuid = SecureRandom.uuid) while self[:uuid].blank? || self.class.exists?(uuid: self[:uuid])
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
federails-0.4.0 app/models/concerns/federails/has_uuid.rb
federails-0.3.0 app/models/concerns/federails/has_uuid.rb
federails-0.2.0 app/models/concerns/federails/has_uuid.rb