Class: TableTennis::Table

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Util::Inspectable
Defined in:
lib/table_tennis/table.rb

Overview

Public API for TableTennis.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Util::Inspectable

#inspect

Constructor Details

#initialize(rows, options = {}, &block) ⇒ Table

Create a new table with options (see Config or README). This is typically called using TableTennis.new.



19
20
21
22
23
24
# File 'lib/table_tennis/table.rb', line 19

def initialize(rows, options = {}, &block)
  config = Config.new(options, &block)
  @data = TableData.new(config:, rows:)
  sanity!
  save(config.save) if config.save
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



13
14
15
# File 'lib/table_tennis/table.rb', line 13

def data
  @data
end

Instance Method Details

#render(io = $stdout) ⇒ Object

Render the table to $stdout or another IO object.



27
28
29
30
31
32
33
34
# File 'lib/table_tennis/table.rb', line 27

def render(io = $stdout)
  %w[format layout painter render].each do |stage|
    args = [].tap do
      _1 << io if stage == "render"
    end
    Stage.const_get(stage.capitalize).new(data).run(*args)
  end
end

#save(path) ⇒ Object

Save the table as a CSV file. Users can also do this manually.



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/table_tennis/table.rb', line 37

def save(path)
  headers = column_names
  CSV.open(path, "wb", headers:, write_headers: true) do |csv|
    rows.each do |row|
      # strip hyperlinks
      row = row.map do |value|
        if value.is_a?(String) && (h = Util::Strings.hyperlink(value))
          value = h[1]
        end
        value
      end
      csv << row
    end
  end
end

#to_sObject

Calls render to convert the table to a string.



54
55
56
# File 'lib/table_tennis/table.rb', line 54

def to_s
  StringIO.new.tap { render(_1) }.string
end