summaryrefslogtreecommitdiff
path: root/app/validators/feature_flag_user_xids_validator.rb
blob: a840993a94b379a2178c3818109b4ca7fa54564c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# frozen_string_literal: true

class FeatureFlagUserXidsValidator < ActiveModel::EachValidator
  USERXID_MAX_LENGTH = 256

  def validate_each(record, attribute, value)
    self.class.validate_user_xids(record, attribute, value, attribute)
  end

  class << self
    def validate_user_xids(record, attribute, user_xids, error_message_attribute_name)
      unless user_xids.is_a?(String) && !user_xids.match(/[\n\r\t]|,,/) && valid_xids?(user_xids.split(","))
        record.errors.add(attribute,
                          "#{error_message_attribute_name} must be a string of unique comma separated values each #{USERXID_MAX_LENGTH} characters or less")
      end
    end

    private

    def valid_xids?(user_xids)
      user_xids.uniq.length == user_xids.length &&
        user_xids.all? { |xid| valid_xid?(xid) }
    end

    def valid_xid?(user_xid)
      user_xid.present? &&
        user_xid.strip == user_xid &&
        user_xid.length <= USERXID_MAX_LENGTH
    end
  end
end