Module: Wrap

Defined in:
lib/svn_campfire_notifier/wrap.rb

Class Method Summary collapse

Class Method Details

.wrap(str, max_size = 80) ⇒ Object



2
3
4
5
6
# File 'lib/svn_campfire_notifier/wrap.rb', line 2

def self.wrap(str, max_size=80)
  str.split("\n").map do |line|
    String.from_chars wrap_chars(line.chars, max_size)
  end.join("\n")
end

.wrap_chars(chars, max_size = 80) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/svn_campfire_notifier/wrap.rb', line 8

def self.wrap_chars(chars, max_size=80)
  space_char = " ".chars.first
  if chars.length > max_size and chars.include?(space_char)
    # If we find a space left of max_size
    if last_whitespace_index = chars[0...max_size].rindex(space_char)
      left = chars[0...last_whitespace_index]
      right = wrap_chars(chars[last_whitespace_index+1..-1], max_size)
      left.empty? ? right : left + " \n".chars + right
    # If we find a space right of max_size
    elsif last_whitespace_index = chars[max_size..-1].index(space_char)
      last_whitespace_index += max_size
      left = wrap_chars(chars[0...last_whitespace_index], max_size)
      right = wrap_chars(chars[last_whitespace_index+1..-1], max_size)
      left.empty? ? right : left + " \n".chars + right
    else
      raise "We lost characters from the string, did it changes inbetween?"
    end
  else
    chars
  end
end