Class: Array::TableChars

Inherits:
Hash
  • Object
show all
Defined in:
lib/array/formatter.rb

Overview

string = ARRAY.to_table type

Convert an array of arrays to ASCII table representation

to create a box, we need to describe the parts of it: (be sure to used fixed-width font)

+-------+-------+  <== top border
| cell1 | cell2 |  <== data row
+-------+-------+  <== inner border
| r2c1  | r2c2  |  <== data row
+-------+-------+  <== bottom border
^       ^       ^
|       |       +--<== right
|       +----------<== middle
+------------------<== left

Given these, there are 15 specific characters for line drawing:

   Location          Symbol          Location          Symbol
================     ======       ================     ======
  top-left-border     tlb           left-inner-border   lib
  top-border           tb                inner-border    ib
  top-inner-border    tib         middle-inner-border   mib
  top-right-border    trb          right-inner-border   rib

  left-data-border    ldb          bottom-left-border   blb
 inner-data-border    idb          bottom-border         bb
 right-data-border    rdb          bottom-inner-border  bib
                                   bottom-right-border  brb

In the specs below, the characters are given in the same order as above. The characters are index by the given symbols.

Constant Summary collapse

@@table_chars =
{}
@@table_char_names =
%w( tlb tb tib trb ldb idb rdb lib ib mib rib blb bb bib brb ).map{|n|n.intern}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, fmt_chars, start = nil, stop = nil) ⇒ TableChars

Returns a new instance of TableChars.



98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/array/formatter.rb', line 98

def initialize name, fmt_chars, start=nil, stop=nil
  @chars = self
  @@table_chars[name] = @chars
  if fmt_chars.class == Symbol
    @@table_chars[name] = @chars = @@table_chars[fmt_chars].dup
  elsif fmt_chars.class == Array
    chars = fmt_chars.dup
    @@table_char_names.each{|n| @chars[n] = chars.shift || raise(ArgumentError, "Missing characters from table drawing charset!")}
  end
  @start = start
  @stop = stop
  @chars
end

Instance Attribute Details

#startObject (readonly)

Returns the value of attribute start.



124
125
126
# File 'lib/array/formatter.rb', line 124

def start
  @start
end

#stopObject (readonly)

Returns the value of attribute stop.



124
125
126
# File 'lib/array/formatter.rb', line 124

def stop
  @stop
end

Class Method Details

.get(name) ⇒ Object

TableChars.get NAME

Return the TableChars object for NAME, or nil



120
121
122
# File 'lib/array/formatter.rb', line 120

def self.get name
  @chars = @@table_chars[name]
end

Instance Method Details

#wrap(text) ⇒ Object



126
127
128
# File 'lib/array/formatter.rb', line 126

def wrap text
  (@start || '') + text + (@stop || '')
end