Module: CMDx::Validators::Inclusion

Extended by:
Inclusion
Included in:
Inclusion
Defined in:
lib/cmdx/validators/inclusion.rb

Overview

Validates that a value is within an enumerable or ‘Range`. Range uses `#cover?`; other enumerables use `===` (so regex/class matchers work).

Instance Method Summary collapse

Instance Method Details

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

Parameters:

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

Options Hash (options):

  • :in (Range, Array, Set, Enumerable)

    allowed values

  • :within (Range, Array, Set, Enumerable)

    alias for ‘:in`

  • :message (String)

    global failure-message override

  • :of_message (String)

    override for enumerable failures

  • :in_message, (String)

    :within_message overrides for range failures

Returns:

Raises:

  • (ArgumentError)

    when neither ‘:in` nor `:within` is given



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/cmdx/validators/inclusion.rb', line 20

def call(value, options = EMPTY_HASH)
  values = options[:in] || options[:within]
  if values.nil?
    raise ArgumentError, <<~MSG.chomp
      inclusion validator requires :in or :within (got #{options.keys.inspect}).
      See https://drexed.github.io/cmdx/inputs/validations/#inclusion
    MSG
  elsif values.is_a?(Hash)
    raise ArgumentError, <<~MSG.chomp
      inclusion validator :in/:within does not accept a Hash; pass an Array,
      Set, Range, or other Enumerable (e.g. `#{values.inspect}.keys`).
      See https://drexed.github.io/cmdx/inputs/validations/#inclusion
    MSG
  end

  if values.is_a?(Range)
    within_failure(values.begin, values.end, options) unless values.cover?(value)
  else
    enum = values.is_a?(Enumerable) ? values : [values]
    of_failure(enum, options) if enum.none? { |v| v === value }
  end
end