class FastestServer::Formatter
Public Class Methods
new(stats)
click to toggle source
# File lib/fastest_server/formatter.rb, line 4 def initialize(stats) @stats = stats s = stats.max_by {|stat| stat[:site].length} @site_max_width = s[:site].length + 1 end
Public Instance Methods
display!(verbose)
click to toggle source
# File lib/fastest_server/formatter.rb, line 18 def display!(verbose) sort! puts formatted! if verbose puts @stats.first[:server] end
formatted!()
click to toggle source
# File lib/fastest_server/formatter.rb, line 10 def formatted! return @formatted if @formatted header = header_format % ["Site", "IP", "Average", "Stddev", "Loss", "Status"] rows = [header, "-" * header.length] rows += @stats.map {|stat| format_row(stat)} @formatted = rows.join("\n") end
Private Instance Methods
almost_same?(f1, f2, tolerence)
click to toggle source
# File lib/fastest_server/formatter.rb, line 26 def almost_same?(f1, f2, tolerence) (f1 - f2).abs <= tolerence end
compare(s1, s2)
click to toggle source
ensure both s1 and s2 are valid hash
# File lib/fastest_server/formatter.rb, line 31 def compare(s1, s2) return 1 unless s1[:status] == 0 return -1 unless s2[:status] == 0 if almost_same?(s1[:avg], s2[:avg], 15) && almost_same?(s1[:stddev], s2[:stddev], 10) s1[:loss] <=> s2[:loss] else s1[:avg] <=> s2[:avg] end end
format_row(stat)
click to toggle source
# File lib/fastest_server/formatter.rb, line 56 def format_row stat row_format % [stat[:site], stat[:ip], stat[:avg], stat[:stddev], stat[:loss], '%', stat[:status]] end
header_format()
click to toggle source
# File lib/fastest_server/formatter.rb, line 48 def header_format "%#{@site_max_width}s %-16s%8s %6s %6s %6s" end
row_format()
click to toggle source
# File lib/fastest_server/formatter.rb, line 52 def row_format "%#{@site_max_width}s %16s %8.2f %6.2f %6.2f%s %6d" end
sort!()
click to toggle source
# File lib/fastest_server/formatter.rb, line 42 def sort! return if @sorted @stats.sort! {|s1, s2| compare(s1, s2)} @sorted = true end