Module: TableTennis::Util::Strings

Includes:
MemoWise
Defined in:
lib/table_tennis/util/strings.rb

Overview

Helpers for measuring and truncating strings.

Constant Summary collapse

SIMPLE =

note that escape e (0x1b) is excluded

/\A[\x00-\x1a\x1c-\x7F–—…·‘’“”•áéíñóúÓ]*\Z/

Class Method Summary collapse

Class Method Details

.center(str, width) ⇒ Object

center text, like String#center but works with painted strings



36
37
38
39
40
41
42
# File 'lib/table_tennis/util/strings.rb', line 36

def center(str, width)
  # artificially inflate width to include escape codes
  if painted?(str)
    width += str.length - unpaint(str).length
  end
  str.center(width)
end


44
45
46
47
48
49
50
# File 'lib/table_tennis/util/strings.rb', line 44

def hyperlink(str)
  # fail fast, for speed
  return unless str.length >= 6 && str[0] == "["
  if str =~ /^\[(.*)\]\((.*)\)$/
    [$1, $2]
  end
end

.painted?(str) ⇒ Boolean

does this string contain ansi codes?

Returns:

  • (Boolean)


10
# File 'lib/table_tennis/util/strings.rb', line 10

def painted?(str) = str.match?(/\e/)

.titleize(str) ⇒ Object

similar to rails titleize



16
17
18
19
20
21
22
# File 'lib/table_tennis/util/strings.rb', line 16

def titleize(str)
  str = str.gsub(/_id$/, "") # remove _id
  str = str.tr("_", " ") # remove underscores
  str = str.gsub(/(\w)([A-Z])/, '\1 \2') # OneTwo => One Two
  str = str.split.map(&:capitalize).join(" ") # capitalize
  str
end

.truncate(str, stop) ⇒ Object

truncate a string based on the display width of the grapheme clusters. Should handle emojis and international characters. Painted strings too.



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/table_tennis/util/strings.rb', line 54

def truncate(str, stop)
  if simple?(str)
    (str.length > stop) ? "#{str[0, stop - 1]}" : str
  elsif painted?(str)
    # generate truncated plain version
    plain = truncate0(unpaint(str), stop)
    # make a best effort to apply the colors
    if (opening_codes = str[/\e\[(?:[0-9];?)+m/])
      "#{opening_codes}#{plain}#{Paint::NOTHING}"
    else
      plain
    end
  else
    truncate0(str, stop)
  end
end

.unpaint(str) ⇒ Object

strip ansi codes



13
# File 'lib/table_tennis/util/strings.rb', line 13

def unpaint(str) = str.gsub(/\e\[[0-9;]*m/, "")

.width(str) ⇒ Object

measure width of text, with support for emojis, painted/ansi strings, etc



25
26
27
28
29
30
31
32
33
# File 'lib/table_tennis/util/strings.rb', line 25

def width(str)
  if simple?(str)
    str.length
  elsif painted?(str)
    unpaint(str).length
  else
    Unicode::DisplayWidth.of(str)
  end
end