Class: WavefrontSparkline
- Inherits:
-
Object
- Object
- WavefrontSparkline
- Defined in:
- lib/wavefront-cli/display/printer/sparkline.rb
Overview
A class to create very simple single-row sparklines of a Wavefront result.
Instance Attribute Summary collapse
-
#sparkline ⇒ Object
readonly
Returns the value of attribute sparkline.
Instance Method Summary collapse
-
#generate_sparkline(data) ⇒ String
The sparkline itself.
-
#initialize(series) ⇒ WavefrontSparkline
constructor
A new instance of WavefrontSparkline.
-
#make_fit(vals) ⇒ Array
A recursive function which repeatedly halves a data series until it fits inside SPARK_WIDTH characters.
-
#sized_block(val, range) ⇒ String
The block corresponding to the given value in the given range.
Constructor Details
#initialize(series) ⇒ WavefrontSparkline
Returns a new instance of WavefrontSparkline.
18 19 20 |
# File 'lib/wavefront-cli/display/printer/sparkline.rb', line 18 def initialize(series) @sparkline = ">#{generate_sparkline(series)}<" end |
Instance Attribute Details
#sparkline ⇒ Object (readonly)
Returns the value of attribute sparkline.
16 17 18 |
# File 'lib/wavefront-cli/display/printer/sparkline.rb', line 16 def sparkline @sparkline end |
Instance Method Details
#generate_sparkline(data) ⇒ String
Returns the sparkline itself.
49 50 51 52 53 54 55 56 |
# 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) ⇒ Array
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.
38 39 40 41 42 43 44 |
# 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) ⇒ String
Returns 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.
26 27 28 29 30 |
# 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 |