class OutcomeValidator
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.
@example
let(:user) { User.find_by(id: user_id) } validates :user_id, outcome: { value: 'user.name', presence: true } # user_id.user_name_presence
Public Instance Methods
validate_each(record, attribute, value)
click to toggle source
rubocop: disable Metrics/MethodLength
# 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
Private Instance Methods
message_key(dependency, condition)
click to toggle source
# File lib/tram/validators/outcome_validator.rb, line 41 def message_key(dependency, condition) [dependency, condition.to_s].compact.join("_").to_sym end
valid_in_sandbox(sandbox, attribute, dependent, validator)
click to toggle source
rubocop: enable Metrics/MethodLength
# File lib/tram/validators/outcome_validator.rb, line 35 def valid_in_sandbox(sandbox, attribute, dependent, validator) sandbox.errors.clear validator.validate_each(sandbox, attribute, dependent) sandbox.errors.empty? end