Class: Sparkr::Sparkline
- Inherits:
-
Object
- Object
- Sparkr::Sparkline
- Defined in:
- lib/sparkr/sparkline.rb
Constant Summary collapse
- TICKS =
%w(▁ ▂ ▃ ▄ ▅ ▆ ▇ █)
- DEFAULT_SEPARATOR =
''
Instance Method Summary collapse
-
#format ⇒ Sparkline
Formats all the ticks in the Sparkline with a given block, returns itself.
-
#initialize(_numbers) ⇒ Sparkline
constructor
A new instance of Sparkline.
-
#normalize_numbers(_numbers) ⇒ Fixnum
Returns the normalized equivalent of a given list.
-
#step_height(_numbers) ⇒ Float
The numerical “height” of a single bar “step”.
-
#steps ⇒ Fixnum
The count of steps between the smallest and highest bar.
-
#to_s(sep = nil) ⇒ String
The sparkline, seperated by
sep
(defaults to ”).
Constructor Details
#initialize(_numbers) ⇒ Sparkline
Returns a new instance of Sparkline.
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# File 'lib/sparkr/sparkline.rb', line 8 def initialize(_numbers) if _numbers.empty? @ticks = [] else @original_numbers = _numbers numbers = normalize_numbers(_numbers) one_step = step_height(numbers) @ticks = numbers.map do |n| index = (n / one_step).to_i TICKS[index] end end end |
Instance Method Details
#format ⇒ Sparkline
Formats all the ticks in the Sparkline with a given block, returns itself
Example:
Let’s say you have a list of open and closed issues and want to format it so the open ones are red and the closed ones are green, so you can quickly see how you are doing. Let’s further suppose you use a gem that adds a #color method to String for ANSI coloring.
list = [open_issue_count, closed_issue_count]
sparkline = Sparkr::Sparkline.new(list)
sparkline.format do |tick, count, index|
if index == 0
tick.color(:red)
else
tick.color(:green)
end
end
sparkline.to_s
# => "▁█" (colored, which you can't see)
49 50 51 52 53 54 |
# File 'lib/sparkr/sparkline.rb', line 49 def format @ticks = @ticks.map.with_index do |tick, index| yield tick, @original_numbers[index], index end self end |
#normalize_numbers(_numbers) ⇒ Fixnum
Returns the normalized equivalent of a given list
normalize_numbers([3, 4, 7])
# => [0, 1, 4]
62 63 64 65 66 67 68 |
# File 'lib/sparkr/sparkline.rb', line 62 def normalize_numbers(_numbers) numbers = _numbers.map(&:to_i) min = numbers.min numbers.map do |n| n - min end end |
#step_height(_numbers) ⇒ Float
Returns the numerical “height” of a single bar “step”.
71 72 73 74 75 76 77 78 79 80 |
# File 'lib/sparkr/sparkline.rb', line 71 def step_height(_numbers) min, max = _numbers.minmax actual_height = max - min step = actual_height / steps.to_f if step == 0 1 else step end end |
#steps ⇒ Fixnum
Returns the count of steps between the smallest and highest bar.
83 84 85 |
# File 'lib/sparkr/sparkline.rb', line 83 def steps TICKS.size - 1 end |
#to_s(sep = nil) ⇒ String
Returns the sparkline, seperated by sep
(defaults to ”).
89 90 91 |
# File 'lib/sparkr/sparkline.rb', line 89 def to_s(sep = nil) @ticks.join(sep || DEFAULT_SEPARATOR) end |