Skip to content

Commit

Permalink
Fix printing tables with borders and indentation
Browse files Browse the repository at this point in the history
When printing tables with borders and indentation the resulting markup
was incorrect:

Before:
```
  +------  +--------  +-------+
|   Name | Number | Color |
|   Erik |      1 | green |
  +------  +--------  +-------+
```

After
```
  +------+--------+-------+
  | Name | Number | Color |
  | Erik |      1 | green |
  +------+--------+-------+
```
  • Loading branch information
p8 committed Aug 25, 2023
1 parent a4d99cf commit 2d7e3d9
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
15 changes: 9 additions & 6 deletions lib/thor/shell/table_printer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def print(array)

sentence = truncate(sentence)
sentence << "|" if options[:borders]
stdout.puts sentence
stdout.puts indentation + sentence

end
print_border_separator if options[:borders]
Expand Down Expand Up @@ -66,7 +66,6 @@ def prepare(array)
end
end

@formats[0] = @formats[0].insert(0, " " * @indent)
@formats << "%s"
end

Expand Down Expand Up @@ -95,10 +94,10 @@ def format_cell(column, row_size, index)
end

def print_border_separator
top = @maximas.map do |maxima|
" " * @indent + "+" + "-" * (maxima + 2 * @padding)
separator = @maximas.map do |maxima|
"+" + "-" * (maxima + 2 * @padding)
end
stdout.puts top.join + "+"
stdout.puts indentation + separator.join + "+"
end

def truncate(string)
Expand All @@ -108,11 +107,15 @@ def truncate(string)
if chars.length <= @truncate
chars.join
else
chars[0, @truncate - 3].join + "..."
chars[0, @truncate - 3 - @indent].join + "..."
end
end
end

def indentation
" " * @indent
end

if "".respond_to?(:encode)
def as_unicode
yield
Expand Down
14 changes: 14 additions & 0 deletions spec/shell/basic_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,20 @@ def #456 Lanç...
| Name | Number | Color |
| Erik | 1 | green |
+------+--------+-------+
TABLE
end

it "prints a table with borders and small numbers and right-aligns them" do
table = [
["Name", "Number", "Color"], # rubocop: disable Style/WordArray
["Erik", 1, "green"]
]
content = capture(:stdout) { shell.print_table(table, borders: true, indent: 2) }
expect(content).to eq(<<-TABLE)
+------+--------+-------+
| Name | Number | Color |
| Erik | 1 | green |
+------+--------+-------+
TABLE
end
end
Expand Down

0 comments on commit 2d7e3d9

Please sign in to comment.