Sha256: 5f06fe91c939db5d0c59e2557e126460b22eeb2c0228dc42221e0ed9ce4ca82c

Contents?: true

Size: 1.57 KB

Versions: 2

Compression:

Stored size: 1.57 KB

Contents

require 'command_mapper/types/type'
require 'command_mapper/types/str'

module CommandMapper
  #
  # The base class for both {Option options} and {Argument arguments}.
  #
  class Arg
    # The argument's arg's type.
    #
    # @return [Types::Type, nil]
    attr_reader :type

    #
    # Initializes the argument.
    #
    # @param [Boolean] required
    #   Specifies whether the argument is required or can be omitted.
    #
    # @param [Types::Type, Hash, nil] type
    #
    # @raise [ArgumentError]
    #   The `type` keyword argument was given a `nil` value.
    #
    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

    #
    # Specifies whether the argument value is required.
    #
    # @return [Boolean]
    #
    def required?
      @required
    end

    #
    # Specifies whether the argument value can be omitted.
    #
    # @return [Boolean]
    #
    def optional?
      !@required
    end

    #
    # Validates whether a given value is compatible with the arg.
    #
    # @param [Object] value
    #
    # @return [true, (false, String)]
    #   Returns true if the value is valid, or `false` and a validation error
    #   message if the value is not compatible.
    #
    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

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
command_mapper-0.1.0 lib/command_mapper/arg.rb
command_mapper-0.1.0.pre1 lib/command_mapper/arg.rb