Class: TTY2::Prompt::Question::Validation
- Inherits:
-
Object
- Object
- TTY2::Prompt::Question::Validation
- Defined in:
- lib/tty2/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
- #pattern ⇒ Object readonly
Instance Method Summary collapse
-
#call(input) ⇒ Boolean
Test if the input passes the validation.
-
#coerce(pattern) ⇒ Object
private
Convert validation into known type.
-
#initialize(pattern) ⇒ undefined
constructor
private
Initialize a Validation.
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
22 23 24 |
# File 'lib/tty2/prompt/question/validation.rb', line 22 def initialize(pattern) @pattern = coerce(pattern) end |
Instance Attribute Details
#pattern ⇒ Object (readonly)
13 14 15 |
# File 'lib/tty2/prompt/question/validation.rb', line 13 def pattern @pattern end |
Instance Method Details
#call(input) ⇒ Boolean
Test if the input passes the validation
57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/tty2/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.
34 35 36 37 38 39 40 41 42 43 |
# File 'lib/tty2/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 |