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

Returns a new instance of CompositeValidator.



94
95
96
97
# File 'app/models/delegate_validation.rb', line 94

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

Class Method Details

.construct(*validator_classes) ⇒ Object



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

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

Instance Method Details

#valid?Boolean

Returns:

  • (Boolean)


99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'app/models/delegate_validation.rb', line 99

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?(true)

  @validators.each do |validator|
    validator.errors.each do |error|
      attrib = error.attribute
      message = error.message
      errors.add(attrib, message) unless errors.include?(attrib)
    end
  end

  false
end