class OptParseValidator::OptChoice

Implementation of the Choice Option

Public Class Methods

new(option, attrs = {}) click to toggle source

@param [ Array ] option See OptBase#new @param [ Hash ] attrs

:choices [ Array ] The available choices (mandatory)
:case_sensitive [ Boolean ] Default: false
Calls superclass method OptParseValidator::OptBase::new
# File lib/opt_parse_validator/opts/choice.rb, line 10
def initialize(option, attrs = {})
  raise Error, 'The :choices attribute is mandatory' unless attrs.key?(:choices)
  raise Error, 'The :choices attribute must be an array' unless attrs[:choices].is_a?(Array)

  super(option, attrs)
end

Public Instance Methods

append_help_messages() click to toggle source

@return [ Void ]

# File lib/opt_parse_validator/opts/choice.rb, line 18
def append_help_messages
  super

  option << "Available choices: #{choices.join(', ')}"
end
validate(value) click to toggle source

@return [ String ] If :case_sensitive if false (or nil), the downcased value of the choice will be returned

# File lib/opt_parse_validator/opts/choice.rb, line 27
def validate(value)
  value = +value.to_s

  unless attrs[:case_sensitive]
    value.downcase!
    choices.map!(&:downcase)
  end

  unless choices.include?(value)
    raise Error, "'#{value}' is not a valid choice, expected one " \
                 "of the followings: #{choices.join(',')}"
  end

  value
end