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

#choices, #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



8
9
10
11
12
13
# File 'lib/opt_parse_validator/opts/choice.rb', line 8

def initialize(option, attrs = {})
  fail Error, 'The :choices attribute is mandatory' unless attrs.key?(:choices)
  fail 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)


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

def append_help_messages
  msg = 'Available choices:'

  choices.each do |choice|
    msg += choice.to_s == default.to_s ? " #{choice} (default)," : " #{choice},"
  end

  option << msg[0..-2]
end

#validate(value) ⇒ String

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

Returns:

  • (String)


29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/opt_parse_validator/opts/choice.rb', line 29

def validate(value)
  value = value.to_s

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

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

  value
end