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.



23
24
25
26
27
28
# File 'lib/table_tennis/table.rb', line 23

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.



17
18
19
# File 'lib/table_tennis/table.rb', line 17

def data
  @data
end

Instance Method Details

#render(io = $stdout) ⇒ Object

Render the table to $stdout or another IO object.



31
32
33
34
35
36
37
38
# File 'lib/table_tennis/table.rb', line 31

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.



41
42
43
44
45
46
# File 'lib/table_tennis/table.rb', line 41

def save(path)
  headers = column_names
  CSV.open(path, "wb", headers:, write_headers: true) do |csv|
    rows.each { csv << _1 }
  end
end

#to_sObject

Calls render to convert the table to a string.



49
50
51
# File 'lib/table_tennis/table.rb', line 49

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