lib/muflax/string.rb in muflax-0.2.4 vs lib/muflax/string.rb in muflax-0.2.5

- old
+ new

@@ -16,6 +16,34 @@ end def whackuum str=/\s+/ self.split(str).map(&:strip) end + + ANSIColorRegexp = Regexp.new(/(?: \e \[ \d+ (?: ;\d+)* m )+/x) + + def truncate length, omission: "..." + return self if self.length <= length + + ss = StringScanner.new(self) + out = ss.scan(ANSIColorRegexp) || "" + cut_length = length - omission.str_length + used = 0 + cut_at = 0 + + while used < length and not ss.eos? + out << ss.getch + c = ss.scan(ANSIColorRegexp) + out << c unless c.nil? + used += 1 + + cut_at = out.length if used == cut_length + end + + if not ss.eos? + out = out[0, cut_at] + out << omission + end + + out + end end