Class: CommandMapper::Types::Type

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

Overview

The base type for all command-line argument types.

Custom Types

Custom types can be defined by extending the Type class.

class PortRange < CommandMapper::Types::Type

  def validate(value)
    case value
    when Integer
      true
    when Range
      if value.begin.kind_of?(Integer)
        true
      else
        [false, "port range can only contain Integers"]
      end
    else
      [false, "port range must be an Integer or a Range of Integers"]
    end
  end

  def format(value)
    case value
    when Integer
      "#{value}"
    when Range
      "#{value.begin}-#{value.end}"
    end
  end

end

The custom type can define the following methods:

  • #initialize - accepts additional configuration options.
  • #validate - accepts a value object and returns true (indicating the value is valid) or [false, message] (indicating the value is invalid).
  • #format - accepts a validated value and returns a formatted String.

Once defined, custom Type classes can be used with option or argument and passed in via the type: keyword argument.

option "--ports", value: {required: true, type: PortRange.new}

argument :ports, required: true, type: PortRange.new

Direct Known Subclasses

InputPath, KeyValue, List, Map, Num, Str

Instance Method Summary collapse

Instance Method Details

#format(value) ⇒ String

The default format method for all types.

Parameters:

  • value (#to_s)

    The given value to format.

Returns:

  • (String)

    The String version of the value.


80
81
82
# File 'lib/command_mapper/types/type.rb', line 80

def format(value)
  value.to_s
end

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

The default validate method for all types.

Parameters:

  • The (Object)

    given value to format.

Returns:

  • (true, (false, String))

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


67
68
69
# File 'lib/command_mapper/types/type.rb', line 67

def validate(value)
  true
end