Class: ValidatesStructure::Validator::EnumerableValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- ValidatesStructure::Validator::EnumerableValidator
- Defined in:
- lib/validates-structure.rb
Instance Method Summary collapse
-
#validate_each(record, attribute, values) ⇒ Object
Validates each value in an enumerable class using ActiveModel validations.
Instance Method Details
#validate_each(record, attribute, values) ⇒ Object
Validates each value in an enumerable class using ActiveModel validations. Adapted from a snippet by Milovan Zogovic (stackoverflow.com/a/12744945)
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 |
# File 'lib/validates-structure.rb', line 178 def validate_each(record, attribute, values) return unless values.respond_to?(:each_with_index) values.each_with_index do |value, index| .each do |key, args| = { attributes: attribute } .merge!(args) if args.is_a?(Hash) next if value.nil? && [:allow_nil] next if value.blank? && [:allow_blank] next if key.to_s == "allow_nil" next if key.to_s == "allow_blank" validator_class_name = "#{key.to_s.camelize}Validator" validator_class = self.class.parent.const_get(validator_class_name) validator = validator_class.new() # TODO: There should be a better way! tmp_record = record.dup validator.validate_each(tmp_record, attribute, value) tmp_record.errors.each do |nested_attribute, error| indexed_attribute = nested_attribute.to_s.sub(/^#{attribute}/, "#{attribute}[#{index}]") record.errors.add(indexed_attribute, error) end end end end |