Module: SimpleScripting::Argv

Extended by:
Argv
Included in:
Argv
Defined in:
lib/simple_scripting/argv.rb

Defined Under Namespace

Classes: ArgumentError, ExitWithArgumentsHelpPrinting, ExitWithCommandsHelpPrinting, InvalidCommand

Instance Method Summary collapse

Instance Method Details

#decode(*definition_and_options) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/simple_scripting/argv.rb', line 50

def decode(*definition_and_options)
  params_definition, options = decode_definition_and_options(definition_and_options)

  arguments = options.fetch(:arguments, ARGV)
  long_help = options[:long_help]
  auto_help = options.fetch(:auto_help, true)
  output    = options.fetch(:output, $stdout)
  raise_errors = options.fetch(:raise_errors, false)

  # WATCH OUT! @long_help can also be set in :decode_command!. See issue #17.
  #
  @long_help = long_help

  exit_data = catch(:exit) do
    if params_definition.first.is_a?(Hash)
      return decode_command!(params_definition, arguments, auto_help)
    else
      return decode_arguments!(params_definition, arguments, auto_help)
    end
  end

  exit_data.print_help(output, @long_help)

  nil # to be used with the 'decode(...) || exit' pattern
rescue SimpleScripting::Argv::ArgumentError, OptionParser::InvalidOption => error
  raise if raise_errors
    
  output.puts "Command error!: #{error.message}"
rescue SimpleScripting::Argv::InvalidCommand => error
  raise if raise_errors

  output.puts <<~MESSAGE
    Command error!: #{error.message}"

    Valid commands: #{error.valid_commands.join(", ")}
  MESSAGE
ensure
  @long_help = nil
end