Class: OptParseValidator::OptChoice
- Defined in:
- lib/opt_parse_validator/opts/choice.rb
Overview
Implementation of the Choice Option
Instance Attribute Summary
Attributes inherited from OptBase
Instance Method Summary collapse
- #append_help_messages ⇒ Void
-
#initialize(option, attrs = {}) ⇒ OptChoice
constructor
A new instance of OptChoice.
-
#validate(value) ⇒ String
If :case_sensitive if false (or nil), the downcased value of the choice will be returned.
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.
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_messages ⇒ Void
18 19 20 21 22 |
# File 'lib/opt_parse_validator/opts/choice.rb', line 18 def 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
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 |