Class: OptParseValidator::OptChoice

Inherits:
OptBase
  • Object
show all
Defined in:
lib/opt_parse_validator/opts/choice.rb

Overview

Implementation of the Choice Option

Instance Attribute Summary

Attributes inherited from OptBase

#attrs, #option, #required

Instance Method Summary collapse

Methods inherited from OptBase

#advanced?, #alias?, #choices, #default, #help_message_for_default, #help_messages, #normalize, #required?, #required_unless, #to_long, #to_s, #to_sym, #value_if_empty

Constructor Details

#initialize(option, attrs = {}) ⇒ OptChoice

Returns a new instance of OptChoice.

Parameters:

  • option (Array)

    See OptBase#new

  • attrs (Hash) (defaults to: {})

    :choices [ Array ] The available choices (mandatory) :case_sensitive [ Boolean ] Default: false

Raises:



10
11
12
13
14
15
# 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

Instance Method Details

#append_help_messagesVoid

Returns:

  • (Void)


18
19
20
21
22
# File 'lib/opt_parse_validator/opts/choice.rb', line 18

def append_help_messages
  super

  option << "Available choices: #{choices.join(', ')}"
end

#validate(value) ⇒ String

If :case_sensitive if false (or nil), the downcased value of the choice will be returned

Returns:

  • (String)


27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# 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