Class: OptParseValidator::OptMultiChoices

Inherits:
OptArray show all
Defined in:
lib/opt_parse_validator/opts/multi_choices.rb

Overview

Implementation of the MultiChoices Option

Instance Attribute Summary

Attributes inherited from OptBase

#attrs, #option, #required

Instance Method Summary collapse

Methods inherited from OptArray

#separator

Methods inherited from OptBase

#choices, #default, #required?, #required_unless, #to_long, #to_s, #to_sym, #value_if_empty

Constructor Details

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

Returns a new instance of OptMultiChoices.

Parameters:

  • option (Array)

    See OptBase#new

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

Options Hash (attrs):

  • :choices (Hash)
  • :incompatible (Array<Array>)


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

def initialize(option, attrs = {})
  fail 'The :choices attribute is mandatory' unless attrs.key?(:choices)
  fail 'The :choices attribute must be a hash' unless attrs[:choices].is_a?(Hash)

  super(option, attrs)
end

Instance Method Details

#normalize(value) ⇒ Object

No normalization



69
70
71
# File 'lib/opt_parse_validator/opts/multi_choices.rb', line 69

def normalize(value)
  value
end

#validate(value) ⇒ Hash

Parameters:

  • value (String)

Returns:

  • (Hash)


19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/opt_parse_validator/opts/multi_choices.rb', line 19

def validate(value)
  results = {}

  super(value).each do |item|
    opt = choices[item.to_sym]

    if opt
      opt_value = opt.value_if_empty.nil? ? true : opt.value_if_empty
    else
      opt, opt_value = value_from_pattern(item)
    end

    results[opt.to_sym] = opt.normalize(opt.validate(opt_value))
  end

  verify_compatibility(results)
end

#value_from_pattern(item) ⇒ Array

Returns:

  • (Array)


38
39
40
41
42
43
44
45
46
# File 'lib/opt_parse_validator/opts/multi_choices.rb', line 38

def value_from_pattern(item)
  choices.each do |key, opt|
    next unless item.match(/\A#{key.to_s}(.*)\z/)

    return [opt, Regexp.last_match[1]]
  end

  fail "Unknown choice: #{item}"
end

#verify_compatibility(values) ⇒ Hash

Parameters:

  • values (Hash)

Returns:

  • (Hash)


51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/opt_parse_validator/opts/multi_choices.rb', line 51

def verify_compatibility(values)
  [*attrs[:incompatible]].each do |a|
    last_match = ''

    a.each do |sym|
      next unless values.key?(sym)

      if last_match.empty?
        last_match = sym
      else
        fail "Incompatible choices detected: #{last_match}, #{sym}"
      end
    end
  end
  values
end