Class: TTY::Prompt::Question::Validation

Inherits:
Object
  • Object
show all
Defined in:
lib/tty/prompt/question/validation.rb

Overview

A class representing question validation.

Constant Summary collapse

VALIDATORS =

Available validator names

{
  email: /^[a-z0-9._%+-]+@([a-z0-9-]+\.)+[a-z]{2,6}$/i
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(pattern) ⇒ undefined

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Initialize a Validation

Parameters:

  • pattern (Object)


22
23
24
# File 'lib/tty/prompt/question/validation.rb', line 22

def initialize(pattern)
  @pattern = coerce(pattern)
end

Instance Attribute Details

#patternObject (readonly)



13
14
15
# File 'lib/tty/prompt/question/validation.rb', line 13

def pattern
  @pattern
end

Instance Method Details

#call(input) ⇒ Boolean

Test if the input passes the validation

Examples:

Validation.new(/pattern/)
validation.call(input) # => true

Parameters:

  • input (Object)

    the input to validate

Returns:

  • (Boolean)


57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/tty/prompt/question/validation.rb', line 57

def call(input)
  if pattern.is_a?(String) || pattern.is_a?(Symbol)
    VALIDATORS.key?(pattern.to_sym)
    !VALIDATORS[pattern.to_sym].match(input.to_s).nil?
  elsif pattern.is_a?(Regexp)
    !pattern.match(input.to_s).nil?
  elsif pattern.is_a?(Proc)
    result = pattern.call(input.to_s)
    result.nil? ? false : result
  else false
  end
end

#coerce(pattern) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Convert validation into known type.

Parameters:

  • pattern (Object)

Raises:

  • (TTY::ValidationCoercion)

    raised when failed to convert validation



34
35
36
37
38
39
40
41
42
43
# File 'lib/tty/prompt/question/validation.rb', line 34

def coerce(pattern)
  case pattern
  when String, Symbol, Proc
    pattern
  when Regexp
    Regexp.new(pattern.to_s)
  else
    raise ValidationCoercion, "Wrong type, got #{pattern.class}"
  end
end