70 lines
1.7 KiB
Ruby
70 lines
1.7 KiB
Ruby
# This class is used only in devops_option_parser.
|
|
# It was extracted because #recognize_option_value method became too large.
|
|
# Description and examples of usage are in devops_option_parser.rb.
|
|
class OptionValueRecognizer
|
|
|
|
attr_reader :option_name, :i18n_scope, :attrs
|
|
|
|
def initialize(option_name, i18n_scope, attrs={})
|
|
@option_name, @i18n_scope, @attrs = option_name, i18n_scope, attrs
|
|
|
|
set_type
|
|
set_option_key
|
|
set_description
|
|
set_variable
|
|
set_options_to_recognize
|
|
end
|
|
|
|
def recognize(parser, parsed_options, &block)
|
|
parsed_options[@option_key] = @attrs[:default] if @attrs.keys.include?(:default)
|
|
|
|
parser.on(*@options_to_recognize, @description) do |value|
|
|
value = @attrs[:switch_value] if @type == :switch
|
|
|
|
if block
|
|
block.call(value)
|
|
else
|
|
parsed_options[@option_key] = value
|
|
end
|
|
end
|
|
end
|
|
|
|
private
|
|
|
|
|
|
|
|
def set_type
|
|
@type = @attrs[:type] || :required
|
|
raise "Illegal optional type: '#{@type}'" unless [:required, :optional, :switch].include?(@type)
|
|
if @type == :switch && !@attrs.keys.include?(:switch_value)
|
|
raise 'Missing switch value'
|
|
end
|
|
end
|
|
|
|
def set_option_key
|
|
@option_key = @attrs[:option_key] || option_name.to_sym
|
|
end
|
|
|
|
def set_description
|
|
@description = @attrs[:description] || I18n.t(i18n_scope)
|
|
end
|
|
|
|
def set_variable
|
|
variable = @attrs[:variable] || option_name.upcase
|
|
|
|
@variable = case @type
|
|
when :optional
|
|
" [#{variable}]"
|
|
when :switch
|
|
''
|
|
else # required by default
|
|
" #{variable}"
|
|
end
|
|
end
|
|
|
|
def set_options_to_recognize
|
|
full = "--#{@option_name}#{@variable}"
|
|
@options_to_recognize = [full]
|
|
@options_to_recognize.unshift(@attrs[:short]) if @attrs[:short]
|
|
end
|
|
end |