lib/logging/utils.rb in logging-0.9.0 vs lib/logging/utils.rb in logging-0.9.1

- old
+ new

@@ -38,6 +38,35 @@ when :Symbol; String(val).intern else val end end end +class String + + # call-seq: + # reduce( width, ellipses = '...' ) #=> string + # + # Reduce the size of the current string to the given _width_ by remove + # characters from the middle of ths tring and replacing them with + # _ellipses_. If the _width_ is greater than the length of the string, the + # string is returned unchanged. If the _width_ is less than the length of + # the _ellipses_, then the _ellipses_ are returned. + # + def reduce( width, ellipses = '...') + raise ArgumentError, "width cannot be negative: #{width}" if width < 0 + + return self if length <= width + + remove = length - width + ellipses.length + return ellipses.dup if remove >= length + + left_end = (length + 1 - remove) / 2 + right_start = left_end + remove + + left = self[0,left_end] + right = self[right_start,length-right_start] + + left << ellipses << right + end +end + # EOF