Class: DelegateValidation::CompositeValidator

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Validations
Defined in:
app/models/delegate_validation.rb

Overview

A composite validator that will perform multiple validations across several validator classes.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(target) ⇒ CompositeValidator


88
89
90
91
# File 'app/models/delegate_validation.rb', line 88

def initialize(target)
  @target = target
  @validators = self.class.validator_classes.map { |c| c.new(target) }
end

Class Method Details

.construct(*validator_classes) ⇒ Object


82
83
84
85
86
# File 'app/models/delegate_validation.rb', line 82

def self.construct(*validator_classes)
  Class.new(CompositeValidator).tap do |sub_class|
    sub_class.validator_classes = validator_classes
  end
end

Instance Method Details

#valid?Boolean


93
94
95
96
97
98
99
100
101
# File 'app/models/delegate_validation.rb', line 93

def valid?
  # We have to run over all validators to get all error messages, then we can check they're all valid
  return true if @validators.map(&:valid?).all? { |v| v == true }

  @validators.each do |validator|
    errors.messages.merge!(validator.errors.messages)
  end
  false
end