Sha256: a5c862df0cd6c77b05521623cc49d8b70102ce651a0ceec00a96a45e09af7614

Contents?: true

Size: 1.52 KB

Versions: 7

Compression:

Stored size: 1.52 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 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

  def first limit=1
    if limit == 0      	; ""
    elsif limit >= size	; dup
    else               	; self[0..(limit - 1)]
    end
  end

  def last limit=1
    if limit == 0      	; ""
    elsif limit >= size	; dup
    else               	; self[(-limit)..-1]
    end
  end

  def indent! amount, indent_string = nil, indent_empty_lines = false
    indent_string = indent_string || self[/^[ \t]/] || " "
    re = indent_empty_lines ? /^/ : /^(?!$)/
    gsub!(re, indent_string * amount)
  end

  def indent amount, indent_string = nil, indent_empty_lines = false
    dup.tap { |_| _.indent!(amount, indent_string, indent_empty_lines) }
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
muflax-0.3.6 lib/muflax/string.rb
muflax-0.3.5 lib/muflax/string.rb
muflax-0.3.4 lib/muflax/string.rb
muflax-0.3.3 lib/muflax/string.rb
muflax-0.3.2 lib/muflax/string.rb
muflax-0.3.1 lib/muflax/string.rb
muflax-0.3.0 lib/muflax/string.rb