Method: Cmds.tokenize_value
- Defined in:
- lib/cmds/util/tokenize_value.rb
.tokenize_value(value, **opts) ⇒ Array<String>
turn an option name and value into an array of shell-escaped string token suitable for use in a command.
60 61 62 63 64 65 66 67 68 69 70 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 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 |
# File 'lib/cmds/util/tokenize_value.rb', line 60 def self.tokenize_value value, **opts opts = defaults opts, TOKENIZE_OPT_KEYS case value when nil # `nil` values produces no tokens [] when Array # The PITA one... # # May produce one or multiple tokens. # # Flatten the array value if option is set value = value.flatten if opts[:flatten_array_values] case opts[:array_mode] when :repeat # Encode each entry as it's own token # # [1, 2, 3] => ["1", "2", "3"] # # Pass entries back through for individual tokenization and flatten # so we are sure to return a single-depth array value.map { |entry| tokenize_value entry, **opts }.flatten when :join # Encode all entries as one joined string token # # [1, 2, 3] => ["1,2,3"] # [esc( value.join opts[:array_join_string] )] when :json # Encode JSON dump as single token, single-quoted # # [1, 2, 3] => ["'[1,2,3]'"] [single_quote( JSON.dump value )] else # SOL raise ArgumentError.new binding.erb <<-END Bad `:array_mode` option: <%= opts[:array_mode].pretty_inspect %> Should be :join, :repeat or :json END end # case opts[:array_mode] when Hash # Much the same as array # # May produce one or multiple tokens. # case opts[:hash_mode] when :join # Join the key and value using the option and pass the resulting array # back through to be handled as configured tokenize_value \ value.map { |k, v| [k, v].join opts[:hash_join_string] }, **opts when :json # Encode JSON dump as single token, single-quoted # # [1, 2, 3] => [%{'{"a":1,"b":2,"c":3}'}] [single_quote( JSON.dump value )] else # SOL raise ArgumentError.new binding.erb <<-END Bad `:hash_mode` option: <%= opts[:hash_mode].pretty_inspect %> Should be :join, or :json END end else # We let {Cmds.esc} handle it, and return that as a single token [esc(value)] end end |