Class: TextLayout::Wrap

Inherits:
Object
  • Object
show all
Defined in:
lib/text_layout/wrap.rb

Instance Method Summary collapse

Constructor Details

#initialize(str) ⇒ Wrap

Returns a new instance of Wrap.



2
3
4
# File 'lib/text_layout/wrap.rb', line 2

def initialize(str)
  @str = str
end

Instance Method Details

#layout(width = 80) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/text_layout/wrap.rb', line 6

def layout(width=80)
  raise "width must be greater than 1" if width < 2
  words = @str.scan(/[[:alnum:]]+|./)

  lines = []
  line = ''
  while word = words.shift
    word.lstrip! if line.empty?
    rest_width = width - line.display_width

    if word.display_width <= rest_width
      line += word
      flush = line.display_width == width
    else
      word, rest = split_word(word, rest_width - 1)
      line += word + "-" unless word.empty?
      words.unshift rest
      flush = true
    end

    if flush
      lines << line
      line = ''
    end
  end

  lines << line

  lines.pop if lines.last.empty?

  lines.join("\n")
end