Class: ArgParser::FlagArgument

Inherits:
Argument
  • Object
show all
Defined in:
lib/arg-parser/argument.rb

Overview

A boolean argument that is set if its key is encountered on the command-line. Flag arguments normally default to false, and become true if the argument key is specified. However, it is also possible to define a flag argument that defaults to true, in which case the option can be disabled by pre- pending the argument key with a ‘no-’ prefix, e.g. –no-export can be specified to disable the normally enabled –export flag.

Instance Attribute Summary

Attributes inherited from Argument

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

Instance Method Summary collapse

Methods inherited from Argument

lookup, register, to_key

Constructor Details

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

Creates a new flag argument, which is an argument with a boolean value.

Parameters:

  • key (Symbol)

    The name that will be used for the accessor used to return this argument value in the parse results.

  • desc (String)

    A description for this argument. Appears in the help output that is generated when the user specifies the –help or /? flags on the command-line.

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

    Contains any options that are desired for this argument.

  • block (Block)

    If supplied, the block passed will be invoked after this argument value has been parsed from the command-line. The block will be called with three arguments: this argument definition, the String value read from the command-line for this argument, and a Hash containing the argument values parsed so far. The return value from the block will be used as the argument value parsed from the command-line for this argument. Blocks are usually used when the value to be returned needs to be converted from a String to some other type.



422
423
424
425
# File 'lib/arg-parser/argument.rb', line 422

def initialize(key, desc, opts = {}, &block)
    super
    @usage_value = opts[:usage_value]
end

Instance Method Details

#requiredObject



427
428
429
# File 'lib/arg-parser/argument.rb', line 427

def required
    false
end

#to_sObject



431
432
433
# File 'lib/arg-parser/argument.rb', line 431

def to_s
    "--#{self.default ? 'no-' : ''}#{key}".gsub('_', '-')
end

#to_useObject



435
436
437
438
439
440
441
442
# File 'lib/arg-parser/argument.rb', line 435

def to_use
    sk = short_key ? "-#{short_key}, " : ''
    if @usage_value
        "#{sk}#{@usage_value[0..1] == '--' ? '' : '--'}#{@usage_value}"
    else
        "#{sk}#{self.to_s}"
    end
end