Class: HaveAPI::Validators::Length

Inherits:
HaveAPI::Validator show all
Defined in:
lib/haveapi/validators/length.rb

Overview

Checks the length of a string. It does not have a short form.

Full form:

string :param, length: {
  min: 3,
  max: 10
  message: 'the error message'
}

string :param, length: {
  equals: 8
}

Instance Attribute Summary

Attributes inherited from HaveAPI::Validator

#message, #params

Instance Method Summary collapse

Methods inherited from HaveAPI::Validator

#initialize, name, #reconfigure, takes, use, use?, #useful?, #validate

Constructor Details

This class inherits a constructor from HaveAPI::Validator

Instance Method Details

#describeObject



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/haveapi/validators/length.rb', line 48

def describe
  ret = {
    message: @message
  }

  if @equals
    ret[:equals] = @equals

  else
    ret[:min] = @min if @min
    ret[:max] = @max if @max
  end

  ret
end

#setupObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/haveapi/validators/length.rb', line 20

def setup
  @min = take(:min)
  @max = take(:max)
  @equals = take(:equals)

  if (@min || @max) && @equals
    raise 'cannot mix min/max with equals'

  elsif !@min && !@max && !@equals
    raise 'must use either min, max or equals'
  end

  msg = if @equals
          "length has to be #{@equals}"

        elsif @min && !@max
          "length has to be minimally #{@min}"

        elsif !@min && @max
          "length has to be maximally #{@max}"

        else
          "length has to be in range <#{@min}, #{@max}>"
        end

  @message = take(:message, msg)
end

#valid?(v) ⇒ Boolean

Returns:



64
65
66
67
68
69
70
71
72
# File 'lib/haveapi/validators/length.rb', line 64

def valid?(v)
  len = v.length

  return len == @equals if @equals
  return len >= @min if @min && !@max
  return len <= @max if !@min && @max

  len >= @min && len <= @max
end