lib/sitefuel/extensions/StringFormatting.rb in sitefuel-0.0.0b vs lib/sitefuel/extensions/StringFormatting.rb in sitefuel-0.1.0a

- old
+ new

@@ -1,50 +1,94 @@ # # File:: StringFormatting.rb # Author:: wkm -# Copyright:: 2009 -# License:: GPL +# Copyright:: 2009, Zanoccio LLC. +# License:: GPL version 2.0 (see LICENSE.rb) # -# Adds String#cabbrev for abbreviating strings +# Adds String#cabbrev for abbreviating strings. Note that this function +# correctly supports ANSI sequences in strings (ie. it ignores them when +# computing sizes) # +# Adds String#align for stripping leading whitespace from multiple lines in +# a string. +# +require 'term/ansicolor' + +include Term::ANSIColor + class String + # gives the apparent length of the string (ignoring ASCII sequences) + def visual_length + uncolored.length + end + + + # gives the difference between the actual and apparent length of the string + def visual_length_delta + length - visual_length + end + + + # like #ljust but uses #visual_length for proper ANSI sequence handling + def visual_ljust(width, padding=" ") + ljust(width + visual_length_delta, padding) + end + + + # like #rjust but uses #visual_length for proper ANSI sequence handling + def visual_rjust(width, padding=" ") + rjust(width + visual_length_delta, padding) + end + + + # like #center but uses #visual_length for proper ANSI sequence handling + def visual_center(width, padding=" ") + center(width + visual_length_delta, padding) + end + + # gives an abbreviated form of a string, showing some of the beginning # and some of the end. # # "the quick brown dog".cabbrev 12 # => "the q... dog" def cabbrev(len) - if length <= len + real_length = uncolored.length + if real_length <= len self else - self[0..(len/2-2).floor] + "..." + self[(length - len/2+2) .. (length)] + self[0..(len/2-2).floor] + "..." + self[(real_length - len/2+2) .. (real_length)] end end + # gives an abbreviated form of the string, showing as much of the beginning # as possible # # "the quick brown dog".labbrev 12 # => "the quick ..." def labbrev(len) - if length <= len + if uncolored.length <= len self else self[0..(len-4)] + '...' end end + # gives an abbreviated form of the string, showing as much of the end as # possible # # "the quick brown dog".rabbrev 12 # => "...brown dog" def rabbrev(len) - if length <= len + real_length = uncolored.length + if real_length <= len self else - '...' + self[(length - (len-3)) .. length] + '...' + self[(real_length - (len-3)) .. real_length] end end + # removes leading whitespace from a set of lines, preserving indentation # relative to the first non-empty line def align return self if empty?