Skip to content

Instantly share code, notes, and snippets.

@6temes
Created October 2, 2019 04:23
Show Gist options
  • Save 6temes/d221b36a523f127cefd3661d76257eb2 to your computer and use it in GitHub Desktop.
Save 6temes/d221b36a523f127cefd3661d76257eb2 to your computer and use it in GitHub Desktop.
Validates that only allowed values are added to an array field.
# 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