module Pakyow::Validations::Data::Unique

Validates that the value is unique within its data source.

Public Class Methods

message(**) click to toggle source
# File lib/pakyow/validations/data/unique.rb, line 11
def self.message(**)
  "must be unique"
end
valid?(value, source:, **options) click to toggle source
# File lib/pakyow/validations/data/unique.rb, line 15
def self.valid?(value, source:, **options)
  query = options[:context].app.data.public_send(source).public_send(:"by_#{options[:key]}", value)

  if updating = options[:updating]
    if updating.is_a?(Pakyow::Data::Result)
      query.count == 0 || query.any? { |result|
        result[updating.__proxy.source.class.primary_key_field] == updating[updating.__proxy.source.class.primary_key_field]
      }
    else
      raise ArgumentError, "Expected `#{updating.class}' to be a `Pakyow::Data::Result'"
    end
  else
    query.count == 0
  end
end