module ASFString

This addon must be required before use

Public Class Methods

fix_encoding(text) click to toggle source

fix encoding errors

# File lib/whimsy/asf/string-utils.rb, line 60
def self.fix_encoding(text)
  result = text

  if encoding == Encoding::BINARY
    result = encode('utf-8', invalid: :replace, undef: :replace)
  end

  result
end
mreplace(text, regexp, &block) click to toggle source

replace matched expressions with the result of the block being called

# File lib/whimsy/asf/string-utils.rb, line 32
def self.mreplace(text, regexp, &block)
  matches = []
  off = 0
  while text[off..-1] =~ regexp
    matches << [off, $~]
    off += $~.end($~.size - 1)
  end
  raise 'unmatched' if matches.empty?

  matches.reverse.each do |offset, match|
    slice = text[offset...-1]
    send = (1...match.size).map {|i| slice[match.begin(i)...match.end(i)]}
    if send.length == 1
      recv = block.call(send.first)
      text[offset + match.begin(1)...offset + match.end(1)] = recv
    else
      recv = block.call(*send)
      next unless recv
      (1...match.size).map {|i| [match.begin(i), match.end(i), i - 1]}.sort.
        reverse.each do |start, fin, i|
        text[offset + start...offset + fin] = recv[i]
      end
    end
  end
  text
end
reflow(text, indent=4, len=80) click to toggle source

reflow an indented block indent = number of spaces to indent by (default 4) len = length of line including the indent (default 80)

# File lib/whimsy/asf/string-utils.rb, line 23
def self.reflow(text, indent=4, len=80)
  text.strip.split(/\n\s*\n/).map {|line|
    line.gsub!(/\s+/, ' ')
    line.strip!
    word_wrap(line, len - indent).gsub(/^/, ' ' * indent)
  }.join("\n\n")
end
word_wrap(text, line_width=80) click to toggle source

wrap a text block containing long lines

# File lib/whimsy/asf/string-utils.rb, line 10
def self.word_wrap(text, line_width=80)
  text.split("\n").collect do |line|
    if line.length > line_width
      line.gsub(/(.{1,#{line_width}})(\s+|$)/, "\\1\n").strip
    else
      line
    end
  end * "\n"
end