summaryrefslogtreecommitdiff
path: root/examples/custom_parser_custom_validator.rb
diff options
context:
space:
mode:
Diffstat (limited to 'examples/custom_parser_custom_validator.rb')
-rw-r--r--examples/custom_parser_custom_validator.rb39
1 files changed, 39 insertions, 0 deletions
diff --git a/examples/custom_parser_custom_validator.rb b/examples/custom_parser_custom_validator.rb
new file mode 100644
index 0000000..0744e7b
--- /dev/null
+++ b/examples/custom_parser_custom_validator.rb
@@ -0,0 +1,39 @@
+require 'highline'
+
+cli = HighLine.new
+
+# The parser
+class ArrayOfNumbersFromString
+ def self.parse(string)
+ string.scan(/\d+/).map(&:to_i)
+ end
+end
+
+# The validator
+class ArrayOfNumbersFromStringInRange
+ def self.in?(range)
+ new(range)
+ end
+
+ attr_reader :range
+
+ def initialize(range)
+ @range = range
+ end
+
+ def valid?(answer)
+ ary = ArrayOfNumbersFromString.parse(answer)
+ ary.all? ->(number) { range.include? number }
+ end
+
+ def inspect
+ "in range #@range validator"
+ end
+end
+
+answer = cli.ask("Which number? (0 or <Enter> to skip): ", ArrayOfNumbersFromString) { |q|
+ q.validate = ArrayOfNumbersFromStringInRange.in?(0..10)
+ q.default = 0
+}
+
+puts "Your answer was: #{answer} and it was correctly validated and coerced into an #{answer.class}"