Sha256: e7a817cf7f1d76f4b6056b4e3cf702ef5ba497037714b53f8e59ec711f94074b

Contents?: true

Size: 1.1 KB

Versions: 2

Compression:

Stored size: 1.1 KB

Contents

#!/usr/bin/env ruby
# -*- encoding: utf-8 -*-
# Copyright muflax <mail@muflax.com>, 2013
# License: GNU GPL 3 <http://www.gnu.org/copyleft/gpl.html>

class String
  alias :starts_with? :start_with?
  alias :ends_with?   :end_with?

  def align str=" ", alignment: :left
    self.split("\n").align(str, alignment: alignment).join("\n")
  end

  def align! str=" ", alignment: :left
    self.replace(self.align(str, aligment: alignment))
  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

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
muflax-0.2.6 lib/muflax/string.rb
muflax-0.2.5 lib/muflax/string.rb