Module: Strings::Pad
- Defined in:
- lib/strings/pad.rb
Overview
Responsible for text padding
Constant Summary collapse
- NEWLINE =
"\n"
- SPACE =
" "
- LINE_BREAK =
%r{\r\n|\r|\n}.freeze
Class Method Summary collapse
-
.display_width(string) ⇒ Integer
private
Calculate visible string width.
-
.max_line_length(text, separator) ⇒ Integer
private
Determine maximum length for all multiline content.
-
.pad(text, padding, fill: SPACE, separator: nil) ⇒ String
private
Apply padding to multiline text with ANSI codes.
-
.pad_around(text, padding, fill: SPACE) ⇒ String
private
Apply padding to left and right side of string.
Class Method Details
.display_width(string) ⇒ Integer
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Calculate visible string width
91 92 93 |
# File 'lib/strings/pad.rb', line 91 def display_width(string) Unicode::DisplayWidth.of(Strings::ANSI.sanitize(string)) end |
.max_line_length(text, separator) ⇒ Integer
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Determine maximum length for all multiline content
80 81 82 83 |
# File 'lib/strings/pad.rb', line 80 def max_line_length(text, separator) lines = text.split(separator, -1) display_width(lines.max_by { |line| display_width(line) } || "") end |
.pad(text, padding, fill: SPACE, separator: nil) ⇒ String
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Apply padding to multiline text with ANSI codes
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/strings/pad.rb', line 34 def pad(text, padding, fill: SPACE, separator: nil) padding = Strings::Padder.parse(padding) text_copy = text.dup sep = separator || text[LINE_BREAK] || NEWLINE line_width = max_line_length(text, sep) output = [] filler_line = fill * line_width padding.top.times do output << pad_around(filler_line, padding, fill: fill) end text_copy.split(sep).each do |line| line = line.empty? ? filler_line : line output << pad_around(line, padding, fill: fill) end padding.bottom.times do output << pad_around(filler_line, padding, fill: fill) end output.join(sep) end |
.pad_around(text, padding, fill: SPACE) ⇒ String
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Apply padding to left and right side of string
67 68 69 |
# File 'lib/strings/pad.rb', line 67 def pad_around(text, padding, fill: SPACE) fill * padding.left + text + fill * padding.right end |