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


135
136
137
138
# File 'lib/ark/utility.rb', line 135

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


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

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

#indent(count) ⇒ Object

Indent the current line by count columns


169
170
171
# File 'lib/ark/utility.rb', line 169

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


174
175
176
177
178
# File 'lib/ark/utility.rb', line 174

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

Print the constructed text


188
189
190
# File 'lib/ark/utility.rb', line 188

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

#push(str) ⇒ Object

Push a string onto the current line


141
142
143
144
145
146
147
# File 'lib/ark/utility.rb', line 141

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.


182
183
184
185
# File 'lib/ark/utility.rb', line 182

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

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

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


157
158
159
160
161
162
163
164
165
166
# File 'lib/ark/utility.rb', line 157

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