Class: CommandMapper::Types::KeyValue
- Defined in:
- lib/command_mapper/types/key_value.rb
Overview
Represents a key-value type.
Instance Attribute Summary collapse
-
#key ⇒ Type
readonly
The key's type.
-
#separator ⇒ String
readonly
The separator String between the key and value.
-
#value ⇒ Type
readonly
The value's type.
Instance Method Summary collapse
-
#format(value) ⇒ String
Formats a value into a key-value pair.
-
#initialize(separator: '=', key: Str.new, value: Str.new) ⇒ KeyValue
constructor
Initializes the key-value value type.
-
#validate(value) ⇒ true, (false, String)
Valides the given value.
Constructor Details
#initialize(separator: '=', key: Str.new, value: Str.new) ⇒ KeyValue
Initializes the key-value value type.
44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/command_mapper/types/key_value.rb', line 44 def initialize(separator: '=', key: Str.new, value: Str.new) @separator = separator if key.nil? raise(ArgumentError,"key: keyword cannot be nil") end if value.nil? raise(ArgumentError,"value: keyword cannot be nil") end @key = Types::Type(key) @value = Types::Type(value) end |
Instance Attribute Details
#key ⇒ Type (readonly)
The key's type.
23 24 25 |
# File 'lib/command_mapper/types/key_value.rb', line 23 def key @key end |
#separator ⇒ String (readonly)
The separator String between the key and value.
16 17 18 |
# File 'lib/command_mapper/types/key_value.rb', line 16 def separator @separator end |
#value ⇒ Type (readonly)
The value's type.
30 31 32 |
# File 'lib/command_mapper/types/key_value.rb', line 30 def value @value end |
Instance Method Details
#format(value) ⇒ String
Formats a value into a key-value pair.
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 |
# File 'lib/command_mapper/types/key_value.rb', line 123 def format(value) case value when Hash, Array case value when Hash key, value = value.first when Array key, value = value end "#{@key.format(key)}#{@separator}#{@value.format(value)}" else super(value) end end |
#validate(value) ⇒ true, (false, String)
Valides the given value.
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 |
# File 'lib/command_mapper/types/key_value.rb', line 71 def validate(value) case value when Hash if value.length < 1 return [false, "cannot be empty"] end if value.length > 1 return [false, "cannot contain multiple key:value pairs (#{value.inspect})"] end key, value = value.first when Array if value.length < 2 return [false, "must contain two elements (#{value.inspect})"] end if value.length > 2 return [false, "cannot contain more than two elements (#{value.inspect})"] end key, value = value else return [false, "must be a Hash or an Array (#{value.inspect})"] end valid, = @key.validate(key) unless valid return [false, "key #{}"] end valid, = @value.validate(value) unless valid return [false, "value #{}"] end return true end |