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.

  • value (Type, Hash)

    The list's value type.


34
35
36
37
38
39
40
41
42
43
# File 'lib/command_mapper/types/list.rb', line 34

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)

52
53
54
# File 'lib/command_mapper/types/list.rb', line 52

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.


99
100
101
# File 'lib/command_mapper/types/list.rb', line 99

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.


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

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