Skip to content

Commit 716bfb1

Browse files
authored
switch to reline for width calculations (#60)
* switch to reline for width calculations * add explicit reline dependency (for ruby 3.5+ where it's no longer in stdlib) * add an emoji-based table test
1 parent 273bae7 commit 716bfb1

4 files changed

Lines changed: 22 additions & 5 deletions

File tree

formatador.gemspec

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ Gem::Specification.new do |s|
4949
## List your runtime dependencies here. Runtime dependencies are those
5050
## that are needed for an end user to actually USE your code.
5151
# s.add_dependency('DEPNAME', [">= 1.1.0", "< 2.0.0"])
52+
s.add_dependency('reline')
5253

5354
## List your development dependencies here. Development dependencies are
5455
## those that are only needed during development

lib/formatador.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
require File.join(File.dirname(__FILE__), 'formatador', 'table')
22
require File.join(File.dirname(__FILE__), 'formatador', 'progressbar')
33

4+
require 'reline' # for table char width calculations
5+
46
class Formatador
57

68
VERSION = '1.1.1'

lib/formatador/table.rb

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -80,11 +80,7 @@ def display_compact_table(hashes, keys = nil, **options, &block)
8080
private
8181

8282
def length(value)
83-
if Module.const_defined?(:Unicode) && Unicode.respond_to?(:width)
84-
Unicode.width(value.to_s.gsub(PARSE_REGEX, ''))
85-
else
86-
value.to_s.gsub(PARSE_REGEX, '').chars.reduce(0) { |sum, char| sum += char.bytesize > 1 ? 2 : 1 }
87-
end
83+
Reline::Unicode.calculate_width(value.to_s.gsub(PARSE_REGEX, ''))
8884

8985
rescue NotImplementedError
9086
value.to_s.gsub(PARSE_REGEX, '').chars.reduce(0) { |sum, char| sum += char.bytesize > 1 ? 2 : 1 }

tests/table_tests.rb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,4 +153,22 @@
153153
end
154154
end
155155

156+
output = <<-OUTPUT
157+
+----+
158+
| [bold]a[/] |
159+
+----+
160+
| 1 |
161+
+----+
162+
| 🤷 |
163+
+----+
164+
OUTPUT
165+
output = Formatador.parse(output)
166+
167+
tests("#display_table([{:a => 1}, {:a => '🤷'}])").returns(output) do
168+
capture_stdout do
169+
Formatador.display_table([{:a => 1}, {:a => '🤷'}])
170+
end
171+
end
172+
173+
156174
end

0 commit comments

Comments
 (0)