Class: OrbitalFields::Tokenize::TokenFieldValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/orbital_fields/tokenize.rb

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object

Raises:

  • (ArgumentError)


87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/orbital_fields/tokenize.rb', line 87

def validate_each(record, attribute, value)
  return if value.blank? && !options[:allow_blank].nil? && options[:allow_blank] == true
    
  minimum = options[:minimum].to_i unless options[:minimum].nil?
  minimum ||= 1
  maximum = options[:maximum].to_i unless options[:maximum].nil?
  maximum ||= 0
  seperator = options[:seperator] unless options[:seperator].nil?
  seperator ||= ","
  exclude = nil
  unless options[:exclude].nil?
    exclude = options[:exclude]
    raise ArgumentError, "The exclude option must be the name of an association" unless record.associations.include?(exclude)
    exclude_assoc = record.send(exclude)
    raise "The association given by the exclude_assoc_id option cannot be nil if it is given" if exclude_assoc.nil?
  end
  exclude_assoc ||= nil
  id_regex = options[:id_regex] unless options[:id_regex].nil?
  id_regex = /^[a-f0-9]{24}$/i
  raise ArgumentError, "The id_regex option must be a regular expression" unless id_regex.class == Regexp
  raise ArgumentError, "The id_regex option doesn't match the id of the exclude_assoc_id option" if !exclude_assoc.nil? && exclude_assoc.id.to_s !~ id_regex
  
  # Setup the array
  token_field_array = value.split(seperator)
  
  # Length validations
  record.errors[attribute] << (options[:message] || I18n.t("mongoid.errors.models.#{record.class.to_s.downcase}.attributes.#{attribute.to_s}.too_few_tokens", default: "requires at least #{minimum} #{"entry".pluralize(minimum)}")) if token_field_array.length < minimum
  record.errors[attribute] << (options[:message] || I18n.t("mongoid.errors.models.#{record.class.to_s.downcase}.attributes.#{attribute.to_s}.too_many_tokens", default: "can't have more than #{maximum} #{"entry".pluralize(maximum)}")) if maximum != 0 && token_field_array.length > maximum
  
  # Format validation
  token_field_array.each do |token|
    record.errors[attribute] << (options[:message] || I18n.t("mongoid.errors.models.#{record.class.to_s.downcase}.attributes.#{attribute.to_s}.bad_token", default: "contains an invalid entry")) if token !~ id_regex
  end
  
  # Exclusion validation
  record.errors[attribute] << (options[:message] || I18n.t("mongoid.errors.models.#{record.class.to_s.downcase}.attributes.#{attribute.to_s}.exclude_token", default: "can't include the #{record.class.to_s.downcase}'s #{exclude}")) if !exclude_assoc.nil? && token_field_array.include?(exclude_assoc.id.to_s)
end