class ActiveModel::Validations::NestedValidator
Bases an object’s validity on nested attributes.
@see ActiveModel::Validations::HelperMethods#validates_nested
validates_nested
Private Instance Methods
any()
click to toggle source
# File lib/nested_validator/nested_validator.rb, line 74 def any @any ||= prepare_options(:any) end
except()
click to toggle source
# File lib/nested_validator/nested_validator.rb, line 70 def except @except ||= prepare_options(:except) end
include?(key)
click to toggle source
# File lib/nested_validator/nested_validator.rb, line 54 def include?(key) if only.present? only.include?(key.to_s) elsif except.present? !except.include?(key.to_s) elsif any.present? any.include?(key.to_s) else true end end
include_index?(values)
click to toggle source
# File lib/nested_validator/nested_validator.rb, line 29 def include_index?(values) values.respond_to? :each end
nested_key(prefix, key)
click to toggle source
# File lib/nested_validator/nested_validator.rb, line 50 def nested_key(prefix, key) "#{prefix} #{key}".strip.to_sym end
only()
click to toggle source
# File lib/nested_validator/nested_validator.rb, line 66 def only @only ||= prepare_options(:only) end
prefix(attribute, index, include_index)
click to toggle source
# File lib/nested_validator/nested_validator.rb, line 33 def prefix(attribute, index, include_index) prefix = (options.has_key?(:prefix) ? options[:prefix] : attribute).to_s prefix << "[#{index}]" if include_index prefix end
prepare_options(key)
click to toggle source
# File lib/nested_validator/nested_validator.rb, line 78 def prepare_options(key) Array.wrap(options[key]).map(&:to_s).map{|k| k.split(/\s+|,/)}.flatten.reject(&:blank?) end
record_error(record, prefix, value)
click to toggle source
# File lib/nested_validator/nested_validator.rb, line 39 def record_error(record, prefix, value) if any.present? valid_keys = any - value.errors.keys.map{|k| k.to_s.split.first} return if valid_keys.present? end value.errors.select{|key, _| include?(key)}.each do |key, error| message = [key.to_s, error].join(' ').strip record.errors.add(prefix, message) unless record.errors[prefix].include?(message) end end
validate_each(record, attribute, values)
click to toggle source
# File lib/nested_validator/nested_validator.rb, line 13 def validate_each(record, attribute, values) with_each_value(values) do |index, value| prefix = prefix(attribute, index, include_index?(values)) record_error(record, prefix, value) if value.invalid? end end
with_each_value(values, &block)
click to toggle source
# File lib/nested_validator/nested_validator.rb, line 20 def with_each_value(values, &block) case values when Hash values.each { |key, value| block.call key, value } else Array.wrap(values).each_with_index { |value, index| block.call index, value} end end