class HammerCLI::Options::Normalizers::KeyValueList

Constants

FULL_RE
PAIR_RE

Public Instance Methods

description() click to toggle source
# File lib/hammer_cli/options/normalizers.rb, line 33
def description
  _("Comma-separated list of key=value")
end
format(val) click to toggle source
# File lib/hammer_cli/options/normalizers.rb, line 37
def format(val)
  return {} unless val.is_a?(String)
  return {} if val.empty?

  if valid_key_value?(val)
    parse_key_value(val)
  else
    begin
      formatter = JSONInput.new
      formatter.format(val)
    rescue ArgumentError
      raise ArgumentError, _("Value must be defined as a comma-separated list of key=value or valid JSON.")
    end
  end
end

Private Instance Methods

parse_key_value(val) click to toggle source
# File lib/hammer_cli/options/normalizers.rb, line 59
def parse_key_value(val)
  result = {}
  val.scan(Regexp.new(PAIR_RE)) do |key, value|
    value = value.strip
    value = value.scan(/[^,\[\]]+/) if value.start_with?('[')

    result[key.strip] = strip_value(value)
  end
  result
end
strip_chars(string, chars) click to toggle source
# File lib/hammer_cli/options/normalizers.rb, line 80
def strip_chars(string, chars)
  chars = Regexp.escape(chars)
  string.gsub(/\A[#{chars}]+|[#{chars}]+\z/, '')
end
strip_value(value) click to toggle source
# File lib/hammer_cli/options/normalizers.rb, line 70
def strip_value(value)
  if value.is_a? Array
    value.map do |item|
      strip_chars(item.strip, '"\')
    end
  else
    strip_chars(value.strip, '"\')
  end
end
valid_key_value?(val) click to toggle source
# File lib/hammer_cli/options/normalizers.rb, line 55
def valid_key_value?(val)
  Regexp.new(FULL_RE).match(val)
end