Class: CommandMapper::Types::List

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

Overview

Represents a list type.

Direct Known Subclasses

KeyValueList

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(separator: ',', type: Str.new, allow_empty: false) ⇒ List

Initializes the list type.

Parameters:

  • separator (String) (defaults to: ',')

    The list separator character.

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

    The list's value type.

  • allow_empty (Boolean) (defaults to: false)

    Specifies whether the list type will accept empty values.



37
38
39
40
41
42
43
44
45
# File 'lib/command_mapper/types/list.rb', line 37

def initialize(separator: ',', type: Str.new, allow_empty: false)
  if type.nil?
    raise(ArgumentError,"type: keyword cannot be nil")
  end

  @separator   = separator
  @type        = Types::Type(type)
  @allow_empty = allow_empty
end

Instance Attribute Details

#separatorString (readonly)

The seperator character.

Returns:

  • (String)


16
17
18
# File 'lib/command_mapper/types/list.rb', line 16

def separator
  @separator
end

#typeType (readonly)

The list element type.

Returns:



23
24
25
# File 'lib/command_mapper/types/list.rb', line 23

def type
  @type
end

Instance Method Details

#allow_empty?Boolean

Specifies whether the option's value may accept empty values.

Returns:

  • (Boolean)


54
55
56
# File 'lib/command_mapper/types/list.rb', line 54

def allow_empty?
  @allow_empty
end

#format(value) ⇒ String

Formats the value into a list.

Parameters:

  • value (Object)

    The given value to format.

Returns:

  • (String)

    The formatted list.



101
102
103
# File 'lib/command_mapper/types/list.rb', line 101

def format(value)
  Array(value).map(&@type.method(:format)).join(@separator)
end

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

Validates the value.

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.



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/command_mapper/types/list.rb', line 70

def validate(value)
  values = Array(value)

  if values.empty?
    unless allow_empty?
      return [false, "cannot be empty"]
    end
  end

  values.each do |element|
    valid, message = @type.validate(element)

    unless valid
      return [false, "element #{message}"]
    end
  end

  return true
end