From 064c55b711670de36e099bdb796910345856ab0e Mon Sep 17 00:00:00 2001 From: Sebastian Serth Date: Sun, 17 Oct 2021 18:54:44 +0200 Subject: [PATCH] Add new validator for all elements of an array --- app/validators/array_validator.rb | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 app/validators/array_validator.rb diff --git a/app/validators/array_validator.rb b/app/validators/array_validator.rb new file mode 100644 index 00000000..f8e88414 --- /dev/null +++ b/app/validators/array_validator.rb @@ -0,0 +1,27 @@ +# frozen_string_literal: true + +class ArrayValidator < ActiveModel::EachValidator + # Taken from https://gist.github.com/justalever/73a1b36df8468ec101f54381996fb9d1 + + def validate_each(record, attribute, values) + Array(values).each do |value| + options.each do |key, args| + validator_options = {attributes: attribute} + validator_options.merge!(args) if args.is_a?(Hash) + + next if value.nil? && validator_options[:allow_nil] + next if value.blank? && validator_options[:allow_blank] + + validator_class_name = "#{key.to_s.camelize}Validator" + validator_class = begin + validator_class_name.constantize + rescue NameError + "ActiveModel::Validations::#{validator_class_name}".constantize + end + + validator = validator_class.new(validator_options) + validator.validate_each(record, attribute, value) + end + end + end +end