Class: WavefrontDisplayPrinter::Terse

Inherits:
Object
  • Object
show all
Defined in:
lib/wavefront-cli/display/printer/terse.rb

Overview

Print values which are per-row. The terse listings, primarily

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data, keys) ⇒ Terse

Returns a new instance of Terse.

Parameters:

  • data (Hash)

    data to display, from a response object

  • keys (Array[Symbol])

    keys to display, in order



16
17
18
19
# File 'lib/wavefront-cli/display/printer/terse.rb', line 16

def initialize(data, keys)
  @data = stringify(data, keys)
  @fmt  = format_string(data, keys)
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



11
12
13
# File 'lib/wavefront-cli/display/printer/terse.rb', line 11

def data
  @data
end

Instance Method Details

#format_string(data, keys) ⇒ String

Returns used to format output.

Returns:

  • (String)

    used to format output



23
24
25
# File 'lib/wavefront-cli/display/printer/terse.rb', line 23

def format_string(data, keys)
  keys.map { |k| "%-#{data.longest_value_of(k)}<#{k}>s" }.join('  ')
end

#map_to_string(value) ⇒ String

If we get a hash as a value (tags, for instance) we squash it down to a “key1=val1;key2=val2” kind of string. Note that this doesn’t handle nested hashes. It shouldn’t have to.

Parameters:

  • value (Map, Hash)

    { k1: ‘v1’, k2: ‘v2’ }

Returns:

  • (String)

    ‘k1=v1;k2=v2’



55
56
57
# File 'lib/wavefront-cli/display/printer/terse.rb', line 55

def map_to_string(value)
  value.map { |k, v| "#{k}=#{v}" }.join(';')
end

#stringify(data, keys) ⇒ Object

Flatten nested data.

Parameters:

  • data (Map, Hash)

    data to flatten

  • keys (Array[Symbol])

    keys of interest. We don’t bother working on things we’ll only throw away



32
33
34
# File 'lib/wavefront-cli/display/printer/terse.rb', line 32

def stringify(data, keys)
  data.map { |e| e.tap { keys.each { |k| e[k] = value_as_string(e[k]) } } }
end

#to_sObject

Format every element according to the format string @fmt



61
62
63
64
65
# File 'lib/wavefront-cli/display/printer/terse.rb', line 61

def to_s
  data.map { |e| format(@fmt, e).rstrip }.join("\n")
rescue KeyError
  raise WavefrontCli::Exception::UserError, 'field not found'
end

#value_as_string(value) ⇒ String

Turn a (potentially) more complicated structure into a string

Parameters:

  • value (Object)

Returns:



40
41
42
43
44
45
46
# File 'lib/wavefront-cli/display/printer/terse.rb', line 40

def value_as_string(value)
  return value.join(', ') if value.is_a?(Array)

  return map_to_string(value) if value.is_a?(Map)

  value
end