Created
October 2, 2019 04:23
-
-
Save 6temes/d221b36a523f127cefd3661d76257eb2 to your computer and use it in GitHub Desktop.
Validates that only allowed values are added to an array field.
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
# frozen_string_literal: true | |
class ArrayValidator < ActiveModel::EachValidator | |
ERROR_MESSAGE = 'An array must be supplied in the :is_subset_of option ' \ | |
'of the configuration hash' | |
def validate_each(record, attribute, value) | |
return unless value.is_a? Array | |
return if (value - other).empty? | |
record.errors.add attribute, :inclusion | |
end | |
def check_validity! | |
return if other.is_a? Array | |
raise ArgumentError, ERROR_MESSAGE | |
end | |
private | |
def other | |
@other ||= options[:is_subset_of] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment