Class: ArgParser::KeywordArgument

Inherits:
ValueArgument show all
Defined in:
lib/arg-parser/argument.rb

Overview

An argument that is specified via a keyword prefix; typically used for optional arguments, although Keyword arguments can also be used for mandatory arguments where there is no natural ordering of arguments.

Instance Attribute Summary collapse

Attributes inherited from ValueArgument

#sensitive, #usage_value, #validation

Attributes inherited from Argument

#default, #description, #key, #on_parse, #required, #short_key, #usage_break

Instance Method Summary collapse

Methods inherited from Argument

to_key

Constructor Details

#initialize(key, desc, opts = {}, &block) ⇒ KeywordArgument

Creates a KeywordArgument, which is an argument that must be specified on a command-line using either a long form key (i.e. –key), or optionally, a short-form key (i.e. -k) should one be defined for this argument.

Parameters:

  • key (Symbol)

    the key that will be used to identify this argument value in the parse results.

  • desc (String)

    the description of this argument, displayed in the generated help screen.

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

    a hash of options that govern the behaviour of this argument.

Options Hash (opts):

  • :required (Boolean)

    whether the keyword argument is a required argument that must appear in the command-line. Defaults to false.

  • :value_optional (Boolean)

    whether the keyword argument can be specified without a value. For example, a keyword argument might be used both as a flag, and to override a default value. Specifying the argument without a value would signify that the option is set, but the default value for the option should be used. Defaults to false (keyword argument cannot be specified without a value).



222
223
224
225
226
# File 'lib/arg-parser/argument.rb', line 222

def initialize(key, desc, opts = {}, &block)
    super
    @required = opts.fetch(:required, false)
    @value_optional = opts.fetch(:value_optional, false)
end

Instance Attribute Details

#value_optionalBoolean Also known as: value_optional?

Whether the keyword argument must be specified with a non-missing value.

Returns:

  • (Boolean)

    true if the keyword can be specified without a value.



200
201
202
# File 'lib/arg-parser/argument.rb', line 200

def value_optional
  @value_optional
end

Instance Method Details

#to_sObject



228
229
230
# File 'lib/arg-parser/argument.rb', line 228

def to_s
    "--#{key}".gsub('_', '-')
end

#to_useObject



232
233
234
235
236
# File 'lib/arg-parser/argument.rb', line 232

def to_use
    sk = short_key ? "-#{short_key}, " : ''
    uv = value_optional ? "[#{usage_value}]" : usage_value
    "#{sk}#{self.to_s} #{uv}"
end