Class: TTY::Text::Truncation
- Inherits:
-
Object
- Object
- TTY::Text::Truncation
- Includes:
- Unicode
- Defined in:
- lib/tty/text/truncation.rb
Overview
A class responsible for text truncation operations
Constant Summary collapse
- DEFAULT_TRAILING =
'…'.freeze
- DEFAULT_TRUNCATION_LENGTH =
30.freeze
Instance Attribute Summary collapse
-
#escape ⇒ Object
readonly
Returns the value of attribute escape.
-
#length ⇒ Object
readonly
Returns the value of attribute length.
-
#separator ⇒ Object
readonly
Returns the value of attribute separator.
-
#text ⇒ Object
readonly
Returns the value of attribute text.
-
#trailing ⇒ Object
readonly
Returns the value of attribute trailing.
Instance Method Summary collapse
-
#initialize(text, *args) ⇒ Truncation
constructor
private
Initialize a Truncation.
-
#truncate ⇒ Object
private
Truncate a text.
Methods included from Unicode
#as_unicode, #clean_utf8, #utf8?
Constructor Details
#new(text, value) ⇒ Truncation #new(text, value, options) ⇒ Truncation
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.
Initialize a Truncation
43 44 45 46 47 48 49 50 51 |
# File 'lib/tty/text/truncation.rb', line 43 def initialize(text, *args) = Utils.(args) @text = text @length = .fetch(:length) { DEFAULT_TRUNCATION_LENGTH } @length = args[0] unless args.empty? @separator = .fetch(:separator) { nil } @trailing = .fetch(:trailing) { DEFAULT_TRAILING } @escape = .fetch(:escape) { true } end |
Instance Attribute Details
#escape ⇒ Object (readonly)
Returns the value of attribute escape.
21 22 23 |
# File 'lib/tty/text/truncation.rb', line 21 def escape @escape end |
#length ⇒ Object (readonly)
Returns the value of attribute length.
15 16 17 |
# File 'lib/tty/text/truncation.rb', line 15 def length @length end |
#separator ⇒ Object (readonly)
Returns the value of attribute separator.
17 18 19 |
# File 'lib/tty/text/truncation.rb', line 17 def separator @separator end |
#text ⇒ Object (readonly)
Returns the value of attribute text.
13 14 15 |
# File 'lib/tty/text/truncation.rb', line 13 def text @text end |
#trailing ⇒ Object (readonly)
Returns the value of attribute trailing.
19 20 21 |
# File 'lib/tty/text/truncation.rb', line 19 def trailing @trailing end |
Instance Method Details
#truncate ⇒ Object
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.
Truncate a text
58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/tty/text/truncation.rb', line 58 def truncate return text unless length && length > 0 as_unicode do chars = (escape ? escape_text : text).chars.to_a return chars.join if chars.length <= length stop = chars[0, length_without_trailing].rindex(separator) chars[0, stop || length_without_trailing].join + trailing end end |