lib/tms/space.rb in tms-1.2.0 vs lib/tms/space.rb in tms-1.3.0

- old
+ new

@@ -1,41 +1,50 @@ require 'colored' -module Tms::Space - SIZE_SYMBOLS = %w[B K M G T P E Z Y].freeze - COLORS = [].tap do |colors| - [:white, :black, :yellow, :red].each do |color| - colors << {:foreground => color} - colors << {:foreground => color, :extra => :bold} - end - colors << {:foreground => :yellow, :extra => :reversed} - colors << {:foreground => :red, :extra => :reversed} - end.freeze +module Tms + module Space + SIZE_SYMBOLS = %w[B K M G T P E Z Y].freeze + COLORS = [].tap do |colors| + [:white, :black, :yellow, :red].each do |color| + colors << {:foreground => color} + colors << {:foreground => color, :extra => :bold} + end + colors << {:foreground => :yellow, :extra => :reversed} + colors << {:foreground => :red, :extra => :reversed} + end.freeze + PRECISION = 1 + LENGTH = 4 + PRECISION + 1 + COEF = 1 / Math.log(10) - def space(size, options = {}) - precision = [options[:precision].to_i, 1].max || 2 - length = 4 + precision + (options[:can_be_negative] ? 1 : 0) + EMPTY_SPACE = ' ' * LENGTH + NOT_COUNTED_SPACE = '!' * LENGTH - number = size.to_i - degree = 0 - while number.abs >= 1000 && degree < SIZE_SYMBOLS.length - 1 - degree += 1 - number /= 1024.0 - end + class << self + attr_writer :base10 + def denominator + @denominator ||= @base10 ? 1000.0 : 1024.0 + end - space = "#{(degree == 0 ? number.to_s : "%.#{precision}f" % number).rjust(length)}#{number == 0 ? ' ' : SIZE_SYMBOLS[degree]}" - if options[:color] - unless ''.respond_to?(:red) - require 'toy/fast_gem' - fast_gem 'colored' + def space(size, options = {}) + case size + when false + NOT_COUNTED_SPACE.bold.red + when 0 + EMPTY_SPACE + else + number, degree = size, 0 + while number.abs >= 1000 && degree < SIZE_SYMBOLS.length - 1 + number /= denominator + degree += 1 + end + + space = "#{degree == 0 ? number.to_s : "%.#{PRECISION}f" % number}#{SIZE_SYMBOLS[degree]}".rjust(LENGTH) + if options[:color] + color = [[Math.log(size) * COEF, 1].max.to_i, COLORS.length].min - 1 + space = Colored.colorize(space, COLORS[color]) + end + space + end end - step = options[:color].is_a?(Hash) && options[:color][:step] || 10 - start = options[:color].is_a?(Hash) && options[:color][:start] || 1 - coef = 10.0 / (step * Math.log(10)) - color = [[Math.log(size) * coef - start, 0].max.to_i, COLORS.length - 1].min rescue 0 - Colored.colorize(space, COLORS[color]) - else - space end end - self.extend self end