-
Notifications
You must be signed in to change notification settings - Fork 84
/
store_model_validator.rb
51 lines (43 loc) · 1.71 KB
/
store_model_validator.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# frozen_string_literal: true
require "active_record"
require "store_model/combine_errors_strategies"
module ActiveModel
module Validations
# +StoreModelValidator+ is a subclass of ActiveModel::EachValidator for
# checking StoreModel::Model attributes.
class StoreModelValidator < ActiveModel::EachValidator
# Validates _json_ attribute using the configured strategy or
# invalidates _array_ attribute when at least one element is invalid.
#
# @param record [ApplicationRecord] object to validate
# @param attribute [String] name of the validated attribute
# @param value [Object] value of the validated attribute
def validate_each(record, attribute, value)
if value.nil?
record.errors.add(attribute, :blank)
return
end
case record.type_for_attribute(attribute).type
when :json, :polymorphic
call_json_strategy(record, attribute, value)
when :array, :polymorphic_array
call_array_strategy(record, attribute, value)
end
end
private
def call_json_strategy(record, attribute, value)
strategy.call(attribute, record.errors, value.errors) if value.invalid?(record.validation_context)
end
def call_array_strategy(record, attribute, value)
any_invalid = value.select { |v| v.invalid?(record.validation_context) }.present?
array_strategy.call(attribute, record.errors, value) if any_invalid
end
def strategy
@strategy ||= StoreModel::CombineErrorsStrategies.configure(options)
end
def array_strategy
@array_strategy ||= StoreModel::CombineErrorsStrategies.configure_array(options)
end
end
end
end