Class: Dashes::Grid

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

Instance Method Summary collapse

Constructor Details

#initializeGrid

Returns a new instance of Grid.



215
216
217
218
# File 'lib/dashes.rb', line 215

def initialize
  @nodes = []
  @width = 80
end

Instance Method Details

#add(*nodes) ⇒ Object



220
221
222
223
# File 'lib/dashes.rb', line 220

def add(*nodes)
  @nodes += nodes
  self
end

#to_sObject



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
# File 'lib/dashes.rb', line 230

def to_s
  return '' if @nodes.empty?
  buffer = []
  node_width = [@nodes.map(&:total_width).max, @width].min
  space_matcher = " "*(node_width+1) # 1 for padding
  @nodes.each do |node|
    node = node.clone
    node.width(node_width)
    if (index = buffer.index { |l| l.include?(space_matcher) }) 
      # there's space for the table in a row, fit it in
      col = buffer[index] =~ Regexp.new(space_matcher)
      node.to_s.split("\n").each do |line|
        if buffer[index].nil?
          buffer[index] = "#{" "*@width}"
        end
        new_line = col == 0 ?  "#{line} " : " #{line}"
        buffer[index][col..(col+node_width)] = new_line
        index += 1
      end
    else
      # there's no more room, just add the table below
      rpad = " "*(@width - node_width)
      buffer += node.to_s.split("\n").map { |line| "#{line}#{rpad}" }
    end
  end
  buffer.map(&:rstrip).join("\n")
end

#width(width) ⇒ Object



225
226
227
228
# File 'lib/dashes.rb', line 225

def width(width)
  @width = width
  self
end