Class: Excavator::TableView

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

Defined Under Namespace

Classes: InvalidDataForHeaders

Constant Summary collapse

DEFAULT_DIVIDER =
" | "

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) {|_self| ... } ⇒ TableView

Returns a new instance of TableView.

Yields:

  • (_self)

Yield Parameters:



10
11
12
13
14
15
16
17
18
19
# File 'lib/excavator/table_view.rb', line 10

def initialize(options = {})
  @options = options
  @_title = ""
  @_headers = []
  @_records = []
  @col_widths = Hash.new { |hash, key| hash[key] = 0 }
  @divider = options[:divider] || DEFAULT_DIVIDER

  yield self if block_given?
end

Instance Method Details

#column_formatsObject

Internal



88
89
90
# File 'lib/excavator/table_view.rb', line 88

def column_formats
  @col_widths.collect { |h, width| "%-#{width}s" }
end

#divider(str) ⇒ Object



39
40
41
# File 'lib/excavator/table_view.rb', line 39

def divider(str)
  @divider = str
end

#header(*headers) ⇒ Object



29
30
31
32
33
34
35
36
37
# File 'lib/excavator/table_view.rb', line 29

def header(*headers)
  headers.flatten!

  headers.each do |h|
    index = @_headers.size
    @_headers << h
    @col_widths[h] = h.to_s.size
  end
end


79
80
81
82
83
84
85
# File 'lib/excavator/table_view.rb', line 79

def print_headers(out)
  @_headers.each_with_index do |h, i|
    out << column_formats[i] % h
    out << @divider if i != (@_headers.size - 1)
  end
  out << "\n"
end

#record(*args) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/excavator/table_view.rb', line 43

def record(*args)
  args.flatten!
  if args.size != @_headers.size
    raise InvalidDataForHeaders.new(<<-MSG)
      Number of columns for record (#{args.size}) does not match number
      of headers (#{@_headers.size})
    MSG
  end
  update_column_widths Hash[*@_headers.zip(args).flatten]
  @_records << args
end

#title(t = nil) ⇒ Object



21
22
23
24
25
26
27
# File 'lib/excavator/table_view.rb', line 21

def title(t = nil)
  if t.nil?
    @_title = t
  else
    @_title = t
  end
end

#to_sObject



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/excavator/table_view.rb', line 55

def to_s
  out = ""
  out << @_title << "\n" if !@_title.nil? && @_title != ""

  print_headers out

  @_records.each_with_index do |record|
    record.each_with_index do |val, i|
      out << column_formats[i] % val
      out << @divider if i != (record.size - 1)
    end
    out << "\n"
  end
  out << "\n"

  out
end

#update_column_widths(hash) ⇒ Object



73
74
75
76
77
# File 'lib/excavator/table_view.rb', line 73

def update_column_widths(hash)
  hash.each do |key, val|
    @col_widths[key] = val.size if val && val.size > @col_widths[key]
  end
end