Class: Sequent::Core::Helpers::AssociationValidator

Inherits:
ActiveModel::Validator
  • Object
show all
Defined in:
lib/sequent/core/helpers/association_validator.rb

Overview

Validator for associations. Typically used in Sequent::Core::Command, Sequent::Core::Event and Sequent::Core::ValueObjects.

When you define attrs that are also value object or array(..) then this class is automatically used.

Example:

class RegisterForTrainingCommand < Sequent::Core::Command
  attrs trainee: Person
end

This will register :trainee with the AssociationValidator and is equivilant to

validates_with Sequent::Core::AssociationValidator, associations: [:trainee]

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ AssociationValidator

Returns a new instance of AssociationValidator.



26
27
28
29
# File 'lib/sequent/core/helpers/association_validator.rb', line 26

def initialize(options = {})
  super
  fail "Must provide ':associations' to validate" unless options[:associations].present?
end

Instance Method Details

#validate(record) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/sequent/core/helpers/association_validator.rb', line 31

def validate(record)
  associations = options[:associations]
  associations = [associations] unless associations.instance_of?(Array)
  associations.each do |association|
    value = record.instance_variable_get("@#{association}")
    if value && incorrect_type?(value, record, association)
      record.errors.add(association, "is not of type #{describe_type(record.class.types[association])}")
    elsif value&.is_a?(Array)
      item_type = record.class.types.fetch(association).item_type
      record.errors.add(association, 'is invalid') unless validate_all(value, item_type).all?
    elsif value&.invalid?
      record.errors.add(association, 'is invalid')
    end
  end
end