Class: OutcomeValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/tram/validators/outcome_validator.rb

Overview

Validates attribute by applying validation rule not to the attribute itself, but to another parameter, whose value depends on the attribute.

The resulting error is collected under the attribute’s key, which is necessary to correctly bind the error to the field, that causes the problem.

Examples:

let(:user) { User.find_by(id: user_id) }
validates :user_id, outcome: { value: 'user.name', presence: true }
# user_id.user_name_presence

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object

rubocop: disable Metrics/MethodLength



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/tram/validators/outcome_validator.rb', line 15

def validate_each(record, attribute, value)
  dependency = options[:value].to_s.gsub(".", "_")
  dependent  = Tram::Validators.chained_value(record, options[:value])
  validators = Tram::Validators.validators(@attributes, options, :value)

  sandbox = record.dup
  validators.each do |condition, validator|
    next if valid_in_sandbox(sandbox, attribute, dependent, validator)

    key = message_key(dependency, condition)
    record.errors.add attribute, key, model:       record,
                                      attribute:   attribute,
                                      value:       value,
                                      delependent: dependent
  end
end