Class: ModelValidator::Validator

Inherits:
Object
  • Object
show all
Defined in:
lib/model_validator/validator.rb

Overview

Validation engine, which fetch, and validate each database records

Instance Method Summary collapse

Constructor Details

#initialize(handlers: [], skip_models: []) ⇒ Validator

Returns a new instance of Validator.



20
21
22
23
# File 'lib/model_validator/validator.rb', line 20

def initialize(handlers: [], skip_models: [])
  @handlers = handlers
  @skip_models = skip_models
end

Instance Method Details

#classes_to_validateObject



25
26
27
28
29
30
31
32
33
# File 'lib/model_validator/validator.rb', line 25

def classes_to_validate
  raise ApplicationRecordNotFound unless defined?(ApplicationRecord)

  Rails.application.try(:eager_load!) if Rails.env.development?
  ApplicationRecord.descendants
                   .reject(&:abstract_class)
                   .select { |type| type.subclasses.empty? }
                   .reject { |type| @skip_models.include? type }
end

#runObject



35
36
37
38
39
40
41
42
43
# File 'lib/model_validator/validator.rb', line 35

def run
  classes_to_validate.each do |model_class|
    @handlers.each { |h| h.try(:on_new_class, model_class) }
    model_class.unscoped.find_each do |model|
      @handlers.each { |h| h.try(:on_violation, model) } unless model.valid?
      @handlers.each { |h| h.try(:after_validation, model) }
    end
  end
end