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
-
#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
41 42 43 44 45 46 47 48 |
# File 'lib/tty/text/truncation.rb', line 41 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 } end |
Instance Attribute Details
#length ⇒ Object (readonly)
Returns the value of attribute length.
16 17 18 |
# File 'lib/tty/text/truncation.rb', line 16 def length @length end |
#separator ⇒ Object (readonly)
Returns the value of attribute separator.
18 19 20 |
# File 'lib/tty/text/truncation.rb', line 18 def separator @separator end |
#text ⇒ Object (readonly)
Returns the value of attribute text.
14 15 16 |
# File 'lib/tty/text/truncation.rb', line 14 def text @text end |
#trailing ⇒ Object (readonly)
Returns the value of attribute trailing.
20 21 22 |
# File 'lib/tty/text/truncation.rb', line 20 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
55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/tty/text/truncation.rb', line 55 def truncate return text unless length && length > 0 as_unicode do chars = 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 |