Module: CMDx::Validators::Numeric

Extended by:
Numeric
Included in:
Numeric
Defined in:
lib/cmdx/validators/numeric.rb

Overview

Validates a numeric ‘value` against one of: `:within` / `:not_within` / `:in` / `:not_in` (Range), `:min` + `:max`, `:gt` / `:lt` (strict comparison), or `:is` / `:is_not` (exact match). `:gte`, `:lte`, `:eq`, `:not_eq` are accepted as aliases of `:min`, `:max`, `:is`, `:is_not` respectively (with matching `_message` overrides). `nil` fails with `:nil_message` override or default.

Instance Method Summary collapse

Instance Method Details

#call(value, options = EMPTY_HASH) ⇒ Validators::Failure?

Parameters:

  • value (Numeric, nil)
  • options (Hash{Symbol => Object}) (defaults to: EMPTY_HASH)

    see module summary

Options Hash (options):

  • :message (String)

    global failure-message override

  • :nil_message (String)

    override when ‘value` is nil

  • :within_message, (String)

    :in_message, :not_within_message, :not_in_message, :min_message, :max_message, :gt_message, :lt_message, :is_message, :is_not_message

Returns:

Raises:

  • (ArgumentError)

    when no recognized numeric option is given



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
# File 'lib/cmdx/validators/numeric.rb', line 36

def call(value, options = EMPTY_HASH)
  return nil_failure(options) if value.nil?

  case options = options.transform_keys(ALIASES)
  in within:
    within_failure(within.begin, within.end, options) unless within.cover?(value)
  in not_within:
    not_within_failure(not_within.begin, not_within.end, options) if not_within.cover?(value)
  in in: xin
    within_failure(xin.begin, xin.end, options) unless xin.cover?(value)
  in not_in:
    not_within_failure(not_in.begin, not_in.end, options) if not_in.cover?(value)
  in min:, max:
    within_failure(min, max, options) unless value.between?(min, max)
  in min:
    min_failure(min, options) unless min <= value
  in max:
    max_failure(max, options) unless value <= max
  in gt:
    gt_failure(gt, options) unless gt < value
  in lt:
    lt_failure(lt, options) unless value < lt
  in is:
    is_failure(is, options) unless value == is
  in is_not:
    is_not_failure(is_not, options) if value == is_not
  else
    raise ArgumentError, "unknown numeric validator options given"
  end
end