Class: CommandMapper::Types::Map

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

Overview

Represents a mapping of Ruby values to other String values.

Direct Known Subclasses

Enum

Constant Summary collapse

YesNo =

Maps boolean values to "yes" and "no"

new(true => 'yes', false => 'no')
EnabledDisabled =

Maps boolean values to "enabled" and "disabled"

new(true => 'enabled', false => 'disabled')

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(map) ⇒ Map

Initializes the map value type.

Parameters:

  • map (Hash{Object => String})

    The map of values to Strings.



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

def initialize(map)
  @map = map
end

Instance Attribute Details

#mapHash{Object => String} (readonly)

The map of values to Strings.

Returns:

  • (Hash{Object => String})


15
16
17
# File 'lib/command_mapper/types/map.rb', line 15

def map
  @map
end

Class Method Details

.[](map) ⇒ Map

Creates a new map.

Parameters:

  • map (Hash{Object => String})

    The map of values to Strings.

Returns:



35
36
37
# File 'lib/command_mapper/types/map.rb', line 35

def self.[](map)
  new(map)
end

Instance Method Details

#format(value) ⇒ String

Maps a value.

Parameters:

  • value (Object)

    The given value.

Returns:

  • (String)

    The mapped value.

Raises:

  • (KeyError)

    The given value is not a key or value in the map.



79
80
81
82
83
84
85
86
87
# File 'lib/command_mapper/types/map.rb', line 79

def format(value)
  if @map.has_key?(value)
    super(@map[value])
  elsif @map.has_value?(value)
    super(value)
  else
    raise(KeyError,"value (#{value.inspect}) is not a key or value in the map: #{@map.inspect}")
  end
end

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

Validates a 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.



57
58
59
60
61
62
63
# File 'lib/command_mapper/types/map.rb', line 57

def validate(value)
  unless (@map.has_key?(value) || @map.has_value?(value))
    return [false, "unknown value (#{value.inspect}) must be #{@map.keys.map(&:inspect).join(', ')}, or #{@map.values.map(&:inspect).join(', ')}"]
  end

  return true
end