Module: TableTennis::Util::Strings

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

Overview

Helpers for measuring and truncating strings.

Constant Summary collapse

ANSI_CODE =
/\e\[[0-9;]*m/
ELLIPSIS =
"…"
INVISIBLE =
/\A(\e\[[0-9;]*m|\u200B)*\z/
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



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

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


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

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)


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

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

.titleize(str) ⇒ Object

similar to rails titleize



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

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 characters. Does not attempt to handle graphemes. Should handle emojis and international characters. Painted strings too.



60
61
62
63
64
65
66
67
68
# File 'lib/table_tennis/util/strings.rb', line 60

def truncate(str, stop)
  if str.bytesize <= stop
    str
  elsif simple?(str)
    (str.length <= stop) ? str : "#{str[0, stop - 1]}#{ELLIPSIS}"
  else
    truncate0(str, stop)
  end
end

.unpaint(str) ⇒ Object

strip ansi codes



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

def unpaint(str) = str.gsub(ANSI_CODE, "")

.width(str) ⇒ Object

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



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

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