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, #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 'The :choices attribute is mandatory' unless attrs.key?(:choices)
  fail 'The :choices attribute must be an array' unless attrs[:choices].is_a?(Array)

  super(option, attrs)
end

Instance Method Details

#validate(value) ⇒ String

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

Returns:

  • (String)


18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/opt_parse_validator/opts/choice.rb', line 18

def validate(value)
  value = value.to_s

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

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

  value
end