class WavefrontSparkline

A class to create very simple single-row sparklines of a Wavefront result.

Attributes

sparkline[R]

Public Class Methods

new(series) click to toggle source
# File lib/wavefront-cli/display/printer/sparkline.rb, line 18
def initialize(series)
  @sparkline = '>' + generate_sparkline(series) + '<'
end

Public Instance Methods

generate_sparkline(data) click to toggle source

@param data [Array] a series of [time, value] data points @return [String] the sparkline itself

# File lib/wavefront-cli/display/printer/sparkline.rb, line 49
def generate_sparkline(data)
  values = data.map { |_k, v| v }
  max = values.max || 0
  min = values.min || 0
  v_range = max - min
  values = make_fit(values)
  values.map { |v| sized_block(v - min, v_range) }.join
end
make_fit(vals) click to toggle source

A recursive function which repeatedly halves a data series until it fits inside SPARK_WIDTH characters. It does this by merging adjacent pairs and finding the mean. This is crude. @param vals [Array] a series of values to display @return [Array]

# File lib/wavefront-cli/display/printer/sparkline.rb, line 38
def make_fit(vals)
  return vals if vals.size < SPARK_WIDTH

  vals.<< vals.last if vals.size.odd?
  ret = vals.each_slice(2).with_object([]) { |s, a| a.<< s.sum / 2 }
  make_fit(ret)
end
sized_block(val, range) click to toggle source

@return [String] the block corresponding to the given value in

the given range. The `rescue` clause handles occasions when
Wavefront returns NaN as a value, or if the range is zero.
# File lib/wavefront-cli/display/printer/sparkline.rb, line 26
def sized_block(val, range)
  BLOCKS[(val / range * (BLOCKS.length - 1)).floor]
rescue StandardError
  BLOCKS.first
end