Class: HaveAPI::Validators::Numericality

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

Overview

Checks the value is a number or a string containing only digits.

Full form:

string :param, number: {
  min: 3,
  max: 10,
  step: 2,
  message: 'the error message'
}

Will allow values ‘3`, `5`, `7` and `9`.

string :param, number: {
  min: 3,
  max: 10,
  mod: 2,
}

Will allow values ‘4`, `6`, `8` and `10`.

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



75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/haveapi/validators/numericality.rb', line 75

def describe
  ret = {
    message: @message
  }

  ret[:min] = @min if @min
  ret[:max] = @max if @max
  ret[:step] = @step if @step
  ret[:mod] = @mod if @mod
  ret[:odd] = @odd if @odd
  ret[:even] = @even if @even

  ret
end

#setupObject



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/haveapi/validators/numericality.rb', line 27

def setup
  @min = take(:min)
  @max = take(:max)
  @step = take(:step)
  @mod = take(:mod)
  @even = take(:even)
  @odd = take(:odd)

  msg = if @min && !@max
          "has to be minimally #{@min}"

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

        elsif @min && @max
          "has to be in range <#{@min}, #{@max}>"

        else
          'has to be a number'
        end

  if @step
    msg += '; ' unless msg.empty?
    msg += "in steps of #{@step}"
  end

  if @mod
    msg += '; ' unless msg.empty?
    msg += "mod #{@step} must equal zero"
  end

  if @odd
    msg += '; ' unless msg.empty?
    msg += 'odd'
  end

  if @even
    msg += '; ' unless msg.empty?
    msg += 'even'
  end

  if @odd && @even
    raise 'cannot be both odd and even at the same time'
  end

  @message = take(:message, msg)
end

#valid?(v) ⇒ Boolean

Returns:



90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/haveapi/validators/numericality.rb', line 90

def valid?(v)
  if v.is_a?(::String)
    return false if /\A\d+\z/ !~ v

    v = v.to_i
  end

  ret = true
  ret = false if @min && v < @min
  ret = false if @max && v > @max
  ret = false if @step && (v - (@min || 0)) % @step != 0
  ret = false if @mod && v % @mod != 0
  ret = false if @odd && v.even?
  ret = false if @even && v % 2 > 0
  ret
end