Class: ValidationKit::MixedCaseValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/validation_kit/mixed_case_validator/mixed_case_validator.rb

Constant Summary collapse

ALL_CAPS =
1
ALL_LOWERCASE =
-1

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



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
32
33
34
35
36
37
38
39
40
# File 'lib/validation_kit/mixed_case_validator/mixed_case_validator.rb', line 6

def validate_each(record, attribute, value)
  return if value.nil?
  return if value.gsub(/\W/, "").size < 3 # skip very short words
  error = nil

  if (value.upcase == value)
    error = ALL_CAPS
  elsif (value.downcase == value)
    error = ALL_LOWERCASE
  end

  return if error.nil?

  model_name = record.class.to_s

  item_name = I18n.t("activerecord.models.attributes.#{model_name.underscore}.#{attribute}",
                     :default => nil) or options[:attribute_name] or attribute

  if error == ALL_CAPS
   message = I18n.t("activerecord.errors.models.attributes.#{model_name.underscore}.#{attribute}.all_caps",
               :item => item_name,
               :default => [:"activerecord.errors.models.#{model_name.underscore}.all_caps",
                            options[:all_caps],
                            :'activerecord.errors.messages.all_caps'])
  elsif error == ALL_LOWERCASE
    message = I18n.t("activerecord.errors.models.attributes.#{model_name.underscore}.#{attributes}.all_lowercase",
                :item => item_name,
                :default => [:"activerecord.errors.models.#{model_name.underscore}.all_lowercase",
                             options[:all_lowercase],
                             :'activerecord.errors.messages.all_lowercase'])
  end

  record.errors.add(attribute, message)

end