Created
June 12, 2018 01:14
-
-
Save gomo/08f7205ab1bfb90603f421452539bedf to your computer and use it in GitHub Desktop.
Validator for an array with a whitelist.
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
# app/models/forms/recruit.rb | |
class Forms::Recruit | |
include ActiveModel::Model | |
attr_accessor :job_types | |
validates :job_types, presence: true, white_list: {list: JOB_TYPES, allow_blank: true} | |
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
# app/validators/whitelist_validator.rb | |
# frozen_string_literal: true | |
class WhitelistValidator < ActiveModel::EachValidator | |
def validate_each(record, attribute, value) | |
return if options[:allow_empty] && value.blank? | |
return record.errors.add(attribute, :inclusion) if value.blank? | |
record.errors.add(attribute, :inclusion) if value.any?{|v| options[:list].exclude?(v)} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment