Class: SoftValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/soft_validator.rb

Defined Under Namespace

Classes: LogSubscriber, Railtie

Constant Summary collapse

VERSION =
File.read(File.join(__dir__, "..", "VERSION")).strip.freeze
ERROR_EVENT =
"validation_error.soft_validator"

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ SoftValidator

Returns a new instance of SoftValidator.



24
25
26
27
# File 'lib/soft_validator.rb', line 24

def initialize(options)
  super
  @validators = wrapped_validators(options[:class])
end

Class Attribute Details

.enforced=(value) ⇒ Object (writeonly)

Sets the attribute enforced

Parameters:

  • value

    the value to set the attribute enforced to.



15
16
17
# File 'lib/soft_validator.rb', line 15

def enforced=(value)
  @enforced = value
end

Class Method Details

.enforced?Boolean

Returns:

  • (Boolean)


11
12
13
# File 'lib/soft_validator.rb', line 11

def enforced?
  @enforced ||= false
end

.subscribe(&block) ⇒ Object



17
18
19
20
21
# File 'lib/soft_validator.rb', line 17

def subscribe(&block)
  ActiveSupport::Notifications.subscribe(ERROR_EVENT) do |event|
    yield(event.payload[:error])
  end
end

Instance Method Details

#enforced?Boolean

Returns:

  • (Boolean)


42
43
44
45
46
# File 'lib/soft_validator.rb', line 42

def enforced?
  enforced = options[:enforced]
  enforced = enforced.call if enforced.is_a?(Proc)
  enforced || self.class.enforced?
end

#validate_each(record, attribute, value) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/soft_validator.rb', line 29

def validate_each(record, attribute, value)
  existing_errors = record.errors.errors.dup
  @validators.each do |validator|
    validator.validate_each(record, attribute, value)
    next if enforced?

    (record.errors.errors - existing_errors).each do |error|
      record.errors.delete(error.attribute, error.type, **error.options)
      ActiveSupport::Notifications.instrument(ERROR_EVENT, error: error)
    end
  end
end