Class: Errapi::Validations::Length

Inherits:
Base
  • Object
show all
Defined in:
lib/errapi/validations/length.rb

Constant Summary collapse

CHECKS =
{ is: :==, minimum: :>=, maximum: :<= }.freeze
REASONS =
{ is: :wrong_length, minimum: :too_short, maximum: :too_long }.freeze

Instance Method Summary collapse

Methods inherited from Base

#actual_option_value, #callable_option_type_error, #callable_option_value?, #callable_option_value_error, #exactly_one_option?

Constructor Details

#initialize(options = {}) ⇒ Length

Returns a new instance of Length.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/errapi/validations/length.rb', line 6

def initialize options = {}

  constraints = options.select{ |k,v| OPTIONS.include? k }
  if constraints.empty?
    raise ArgumentError, "The :is, :minimum/:maximum or :within options must be supplied (but only :minimum and :maximum can be used together)."
  elsif options.key?(:is) && constraints.length != 1
    raise ArgumentError, "The :is option cannot be combined with :minimum, :maximum or :within."
  elsif options.key?(:is)
    check_numeric! options[:is]
  elsif options.key?(:within)
    if options.key?(:minimum) || options.key?(:maximum)
      raise ArgumentError, "The :within option cannot be combined with :minimum or :maximum."
    else
      check_range! options[:within]
    end
  else
    check_numeric! options[:minimum] if options.key? :minimum
    check_numeric! options[:maximum] if options.key? :maximum
  end

  @constraints = actual_constraints constraints
end

Instance Method Details

#validate(value, context, options = {}) ⇒ Object



29
30
31
32
33
34
35
36
37
38
# File 'lib/errapi/validations/length.rb', line 29

def validate value, context, options = {}
  return unless value.respond_to? :length
  actual_length = value.length

  CHECKS.each_pair do |key,check|
    next unless check_value = @constraints[key]
    next if actual_length.send check, check_value
    context.add_error reason: REASONS[key], check_value: check_value, checked_value: actual_length, constraints: @constraints
  end
end