Class: Ark::TextBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/ark/utility.rb

Overview

Build text progressively, line by line

Instance Method Summary collapse

Constructor Details

#initializeTextBuilder

Initialize a TextBuilder instance



108
109
110
111
# File 'lib/ark/utility.rb', line 108

def initialize()
  @lines = [[]]
  @line  = 0
end

Instance Method Details

#add(str) ⇒ Object

Add str to the last string on the line. This avoids a space between the strings when the text is printed



124
125
126
# File 'lib/ark/utility.rb', line 124

def add(str)
  @lines[@line][-1] += str.to_s
end

#indent(count) ⇒ Object

Indent the current line by count columns



139
140
141
# File 'lib/ark/utility.rb', line 139

def indent(count)
  @lines[@line].unshift(' ' * (count - 1))
end

#next(str = nil) ⇒ Object

Start a new line. If str is provided, push str onto the new line



144
145
146
147
148
# File 'lib/ark/utility.rb', line 144

def next(str=nil)
  @lines << []
  @line  += 1
  self.push(str) if str
end

Print the constructed text



158
159
160
# File 'lib/ark/utility.rb', line 158

def print()
  @lines.map {|line| line.join(' ') }.join("\n")
end

#push(str) ⇒ Object

Push a string onto the current line



114
115
116
117
118
119
120
# File 'lib/ark/utility.rb', line 114

def push(str)
  if str.is_a?(Array)
    @lines[@line] += str.map(&:to_s)
  else
    @lines[@line] << str.to_s
  end
end

#skip(str = nil) ⇒ Object

Insert a blank line and start the line after it. If str is given, push str onto the new line.



152
153
154
155
# File 'lib/ark/utility.rb', line 152

def skip(str=nil)
  self.next()
  self.next(str)
end

#wrap(width: 78, indent: 0) ⇒ Object

Wrap the current line to width, with an optional indent. After wrapping, the current line will be the last line wrapped.



130
131
132
133
134
135
136
# File 'lib/ark/utility.rb', line 130

def wrap(width: 78, indent: 0)
  text = @lines[@line].join(' ')
  text = Text.wrap(text, width: width, indent: indent)
  @lines.delete_at(@line)
  @line -= 1
  text.split("\n").each {|line| self.next(line) }
end