alias Tablo::Cell::Data::Formatter
Overview
The purpose of the formatter is to transform the raw value of a cell
into a formatted character string
For cells of type Tablo::Cell::Data
, the Formatter Proc can take 4 different
forms, as shown below by their commonly used parameter names and types:
- 1st form : (value :
Tablo::CellType
) - 2nd form : (value :
Tablo::CellType
, column_width :Int32
) - 3rd form : (value :
Tablo::CellType
, coords :Tablo::Cell::Data::Coords
) - 4th form : (value :
Tablo::CellType
, coords :Tablo::Cell::Data::Coords
, column_width :Int32
)
The default formatter is defined byTablo::Config::Defaults.body_formatter
(or
Tablo::Config::Defaults.header_formatter
) and the return type is String for
all of them.
These different forms can be used for conditional formatting.
For example, to alternate case after each row, the 3rd form can be used :
require "tablo"
table = Tablo::Table.new(["A", "B", "C"],
body_formatter: ->(value : Tablo::CellType, coords : Tablo::Cell::Data::Coords) {
if value.is_a?(String)
coords.row_index % 2 == 0 ? value.as(String).upcase : value.as(String).downcase
else
value.to_s
end
}) do |t|
t.add_column("itself", &.itself)
t.add_column("itself x 2", &.*(2))
t.add_column("itself x 3", &.*(3))
end
puts table
+--------------+--------------+--------------+
| itself | itself x 2 | itself x 3 |
+--------------+--------------+--------------+
| A | AA | AAA |
| b | bb | bbb |
| C | CC | CCC |
+--------------+--------------+--------------+
This has an impact on all text columns. To limit formatting to the second column, for example, you could write:
require "tablo"
table = Tablo::Table.new(["A", "B", "C"],
body_formatter: ->(value : Tablo::CellType, coords : Tablo::Cell::Data::Coords) {
if value.is_a?(String) && coords.column_index == 1
coords.row_index % 2 == 0 ? value.as(String).upcase : value.as(String).downcase
else
value.to_s
end
}) do |t|
t.add_column("itself", &.itself)
t.add_column("itself x 2", &.*(2))
t.add_column("itself x 3", &.*(3))
end
puts table
or, if formatting is done directly at the column level:
require "tablo"
table = Tablo::Table.new(["A", "B", "C"]) do |t|
t.add_column("itself", &.itself)
t.add_column("itself x 2",
body_formatter: ->(value : Tablo::CellType, coords : Tablo::Cell::Data::Coords) {
if value.is_a?(String)
coords.row_index % 2 == 0 ? value.as(String).upcase : value.as(String).downcase
else
value.to_s
end
}, &.*(2)
)
t.add_column("itself x 3", &.*(3))
end
puts table
+--------------+--------------+--------------+
| itself | itself x 2 | itself x 3 |
+--------------+--------------+--------------+
| A | AA | AAA |
| B | bb | BBB |
| C | CC | CCC |
+--------------+--------------+--------------+
Alias Definition
Tablo::CellType, Int32 -> String | Tablo::CellType -> String | Tablo::CellType, Tablo::Cell::Data::Coords, Int32 -> String | Tablo::CellType, Tablo::Cell::Data::Coords -> String