Created
January 22, 2021 16:09
-
-
Save stas/23b0376bd07e0e17f67515dec15adfa4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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