Class: HaveAPI::Validators::Numericality
- Inherits:
-
HaveAPI::Validator
- Object
- HaveAPI::Validator
- HaveAPI::Validators::Numericality
- 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
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
#describe ⇒ Object
73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
# File 'lib/haveapi/validators/numericality.rb', line 73 def describe ret = { message: HaveAPI.localize(@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 |
#setup ⇒ Object
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 |
# 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) requirements = [] requirements << if @min && !@max HaveAPI.('haveapi.validators.numericality.min', min: @min) elsif !@min && @max HaveAPI.('haveapi.validators.numericality.max', max: @max) elsif @min && @max HaveAPI.('haveapi.validators.numericality.range', min: @min, max: @max) else HaveAPI.('haveapi.validators.numericality.number') end if @step requirements << HaveAPI.('haveapi.validators.numericality.step', step: @step) end if @mod requirements << HaveAPI.('haveapi.validators.numericality.mod', mod: @mod) end if @odd requirements << HaveAPI.('haveapi.validators.numericality.odd') end if @even requirements << HaveAPI.('haveapi.validators.numericality.even') end if @odd && @even raise 'cannot be both odd and even at the same time' end @message = take( :message, HaveAPI.('haveapi.validators.numericality.composite', requirements:) ) end |
#valid?(v) ⇒ Boolean
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
# File 'lib/haveapi/validators/numericality.rb', line 88 def valid?(v) if v.is_a?(::String) return false if /\A\d+\z/ !~ v v = v.to_i end return false unless v.is_a?(::Numeric) 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 |