Skip to content

Instantly share code, notes, and snippets.

@gomo
Created June 12, 2018 01:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gomo/08f7205ab1bfb90603f421452539bedf to your computer and use it in GitHub Desktop.
Save gomo/08f7205ab1bfb90603f421452539bedf to your computer and use it in GitHub Desktop.
Validator for an array with a whitelist.
# 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
# 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