module HasUuidIdentifier
  UUID_MATCH = /^[0-9A-F]{8}-[0-9A-F]{4}-(?<version>[1-5])[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
  extend ActiveSupport::Concern

  included do
    before_save :ensure_identifier
  end

  module ClassMethods
    def find(*args)
      finder = args.first
      if finder.is_a?(String) and finder.length == 36 and finder =~ UUID_MATCH
        find_by(identifier: finder)
      else
        super
      end
    end
  end

  private

  def ensure_identifier
    self.identifier ||= UUIDTools::UUID.timestamp_create.to_s
  end
end
