Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@stas
Created January 22, 2021 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stas/23b0376bd07e0e17f67515dec15adfa4 to your computer and use it in GitHub Desktop.
Save stas/23b0376bd07e0e17f67515dec15adfa4 to your computer and use it in GitHub Desktop.
require 'active_model/validator'
# Runs [Array] type validations
class ArrayValidator < ActiveModel::EachValidator
# Checks if the value is an [Array] type
#
# Will sort, remove duplicates and blanks as well.
#
# Will validate the subset if passed options are present under `subset_of`.
#
# @return [ActiveModel::Base]
def validate_each(record, attribute, value)
unless value.is_a?(Array)
return record.errors.add(attribute, :invalid)
end
value.map! do |val|
StripAttributes.strip(val, collapse_spaces: true, replace_newlines: true)
end
value.reject!(&:blank?)
value.map(&:downcase!) if options[:downcase]
value.uniq!
value.sort!
return if options[:subset_of].blank?
subset_of = options[:subset_of]
subset_of = subset_of.call if subset_of.respond_to?(:call)
invalid = value.map(&:to_s) - subset_of.map(&:to_s)
return if invalid.blank?
record.errors.add(attribute, :invalid_array, value: invalid.join(','))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment