Created
July 18, 2020 01:16
-
-
Save sankalpk/8291e2abb4b8e92fb51c7b842e6a444a to your computer and use it in GitHub Desktop.
This file contains 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
class ArrayValidator < ActiveModel::EachValidator | |
def validate_each(record, attribute, value) | |
array_elements_are_unique(record, attribute, value) | |
array_elements_are_subset_of_valid_list(record, attribute, value, options[:with]) | |
field_is_present(record, attribute, value) | |
end | |
def array_elements_are_unique(record, attribute, value) | |
if value.present? && (value.uniq.size < value.size) | |
record.errors.add(attribute, 'are duplicated') | |
false | |
else | |
true | |
end | |
end | |
def array_elements_are_subset_of_valid_list(record, attribute, value, valid_list) | |
if (value & valid_list) == value | |
true | |
else | |
record.errors.add(attribute, 'are not valid') | |
end | |
end | |
def field_is_present(record, attribute, value) | |
if !value.nil? && value.try(:size) >= 0 | |
true | |
else | |
record.errors.add(field_name, 'are missing') | |
false | |
end | |
end | |
end |
This file contains 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
class User | |
VALID_RACES = %w[black americanIndian asian pacificIslander white] | |
validates :races, array: { with: VALID_RACES } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment