Module: CMDx::Validators::Length

Extended by:
Length
Included in:
Length
Defined in:
lib/cmdx/validators/length.rb

Overview

Validates the ‘#length` of `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). Values without `#length` fail with the `:nil_message` override or a default.

Instance Method Summary collapse

Instance Method Details

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

Parameters:

  • value (#length, 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` lacks `#length`

  • :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 length option is given



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

def call(value, options = EMPTY_HASH)
  return nil_failure(options) unless value.respond_to?(:length)

  length = value.length

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