Skip to content
Browse files

Add tests for Sparkline#format

  • Loading branch information...
1 parent 7e583b7 commit 1f077efec5e8a567d2f07df2cdc41218b496e92b @rrrene committed Jan 22, 2014
Showing with 67 additions and 1 deletion.
  1. +40 −0 lib/sparkr/sparkline.rb
  2. +27 −1 test/sparkr_test.rb
View
40 lib/sparkr/sparkline.rb
@@ -6,6 +6,8 @@ class Sparkline
DEFAULT_SEPARATOR = ''
def initialize(_numbers)
+ @original_numbers = _numbers
+
numbers = normalize_numbers(_numbers)
one_step = step_height(numbers)
@@ -15,6 +17,44 @@ def initialize(_numbers)
end
end
+ # 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)
+ #
+ # @return [Sparkline] itself
+ def format(&block)
+ new_ticks = []
+ @ticks.each_with_index do |tick, index|
+ if block.arity == 2
+ new_ticks << yield(tick, @original_numbers[index])
+ elsif block.arity == 3
+ new_ticks << yield(tick, @original_numbers[index], index)
+ end
+ end
+ @ticks = new_ticks
+ self
+ end
+
# Returns the normalized equivalent of a given list
#
# normalize_numbers([3,4,7])
View
28 test/sparkr_test.rb
@@ -3,7 +3,7 @@
require File.expand_path(File.dirname(__FILE__) + '/test_helper')
describe ::Sparkr do
- it "should find work" do
+ it "should find work like holman/spark" do
assert_sparkline '▁▂▃▄▅▆▇█', [1,2,3,4,5,6,7,8]
assert_sparkline '▁▂█▅▂', [1,5,22,13,5]
assert_sparkline '▁█', [5.5,20]
@@ -12,7 +12,33 @@
assert_sparkline '▁▃█', [2,4,8]
assert_sparkline '▁▂▃▄▂█', [0,30,55,80,33,150]
assert_sparkline '▁▂▄▆█', [1,2,3,4,5]
+ end
+ it "should find work with equal numbers" do
assert_sparkline '▁▁', [10, 10]
end
+
+ it "format should work with arity == 2" do
+ sparkline = Sparkr::Sparkline.new([5.5,20])
+ sparkline.format do |tick, number|
+ if number < 6.0
+ tick = tick + "-"
+ else
+ tick
+ end
+ end
+ assert_equal '▁-█', sparkline.to_s
+ end
+
+ it "format should work with arity == 3" do
+ sparkline = Sparkr::Sparkline.new([5.5,20])
+ sparkline.format do |tick, number, index|
+ if index == 1
+ tick = tick + "-"
+ else
+ tick
+ end
+ end
+ assert_equal '▁█-', sparkline.to_s
+ end
end

0 comments on commit 1f077ef

Please sign in to comment.
Something went wrong with that request. Please try again.