Sha256: 61b15d970d9ce0f5c68e841e5c7d4b46d7afe25d3906603fb4c3aa0fdde4f4e9

Contents?: true

Size: 779 Bytes

Versions: 9

Compression:

Stored size: 779 Bytes

Contents

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}"

Version data entries

9 entries across 8 versions & 3 rubygems

Version Path
trusty-cms-7.0.9.1 vendor/bundle/ruby/3.1.0/gems/highline-3.1.1/examples/custom_parser_custom_validator.rb
trusty-cms-7.0.9.1 vendor/bundle/ruby/3.3.0/gems/highline-3.1.1/examples/custom_parser_custom_validator.rb
highline-3.1.2 examples/custom_parser_custom_validator.rb
highline-3.1.1 examples/custom_parser_custom_validator.rb
blacklight-spotlight-3.6.0.beta8 vendor/bundle/ruby/3.2.0/gems/highline-3.0.1/examples/custom_parser_custom_validator.rb
highline-3.1.0 examples/custom_parser_custom_validator.rb
highline-3.0.1 examples/custom_parser_custom_validator.rb
highline-3.0.0 examples/custom_parser_custom_validator.rb
highline-3.0.0.pre.1 examples/custom_parser_custom_validator.rb