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.


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

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

Class Method Details

.construct(*validator_classes) ⇒ Object


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

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)

100
101
102
103
104
105
106
# File 'app/models/delegate_validation.rb', line 100

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 { |validator| errors.messages.merge!(validator.errors.messages) }
  false
end