Class: CommandMapper::Arg

Inherits:
Object
  • Object
show all
Defined in:
lib/command_mapper/arg.rb

Overview

The base class for both options and arguments.

Direct Known Subclasses

Argument, OptionValue

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(required: true, type: Types::Str.new) ⇒ Arg

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Initializes the argument.

Parameters:

  • required (Boolean) (defaults to: true)

    Specifies whether the argument is required or can be omitted.

  • type (Types::Type, Hash, nil) (defaults to: Types::Str.new)

    The type of the arg's value.

Raises:

  • (ArgumentError)

    The type keyword argument was given a nil value.



29
30
31
32
33
34
35
36
37
# File 'lib/command_mapper/arg.rb', line 29

def initialize(required: true, type: Types::Str.new)
  @required = required

  if type.nil?
    raise(ArgumentError,"type: keyword cannot be nil")
  end

  @type = Types::Type(type)
end

Instance Attribute Details

#typeTypes::Type? (readonly)

The argument's arg's type.

Returns:



13
14
15
# File 'lib/command_mapper/arg.rb', line 13

def type
  @type
end

Instance Method Details

#optional?Boolean

Specifies whether the argument value can be omitted.

Returns:

  • (Boolean)


53
54
55
# File 'lib/command_mapper/arg.rb', line 53

def optional?
  !@required
end

#required?Boolean

Specifies whether the argument value is required.

Returns:

  • (Boolean)


44
45
46
# File 'lib/command_mapper/arg.rb', line 44

def required?
  @required
end

#validate(value) ⇒ true, (false, String)

Validates whether a given value is compatible with the arg.

Parameters:

  • value (Object)

    The given value to validate.

Returns:

  • (true, (false, String))

    Returns true if the value is valid, or false and a validation error message if the value is not compatible.



69
70
71
72
73
74
75
76
77
78
79
# File 'lib/command_mapper/arg.rb', line 69

def validate(value)
  if value.nil?
    if required?
      return [false, "does not accept a nil value"]
    else
      return true
    end
  else
    return @type.validate(value)
  end
end