Class: Tuning::Validations::CountValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/tuning/validations/count.rb

Constant Summary collapse

MESSAGES =
{ is: :wrong_count, minimum: :too_few, maximum: :too_many }
CHECKS =
{ is: :==, minimum: :>=, maximum: :<= }

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ CountValidator

Returns a new instance of CountValidator.



9
10
11
12
13
14
15
# File 'lib/tuning/validations/count.rb', line 9

def initialize(options)
  if range = (options[:in] || options[:within])
    options[:minimum] = range.min
    options[:maximum] = range.max
  end
  super
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/tuning/validations/count.rb', line 17

def validate_each(record, attribute, value)
  if value.respond_to?(:size)
    count = value.size
    CHECKS.each do |name, operator|
      if options.has_key?(name)
        other = options[name]
        unless count.send(operator, other)
          record.errors.add attribute, MESSAGES[name], count: other
        end
      end
    end
  else
    record.errors.add attribute, :uncountable
  end
end