Class: TTY::Text::Truncation

Inherits:
Object
  • Object
show all
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

Instance Method Summary collapse

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

Overloads:

  • #new(text, value) ⇒ Truncation

    truncates text at given value

    Parameters:

    • value (Integer)
  • #new(text, value, options) ⇒ Truncation

    Parameters:

    • value (Integer)
    • options (Hash)

    Options Hash (options):

    • :length (Symbol)

      the desired length

    • :separator (Symbol)

      the character for splitting words

    • :trailing (Symbol)

      the character for ending sentence

Parameters:

  • text (String)

    the text to be truncated



41
42
43
44
45
46
47
48
# File 'lib/tty/text/truncation.rb', line 41

def initialize(text, *args)
  options    = Utils.extract_options!(args)
  @text      = text
  @length    = options.fetch(:length) { DEFAULT_TRUNCATION_LENGTH }
  @length    = args[0] unless args.empty?
  @separator = options.fetch(:separator) { nil }
  @trailing  = options.fetch(:trailing) { DEFAULT_TRAILING }
end

Instance Attribute Details

#lengthObject (readonly)

Returns the value of attribute length.



16
17
18
# File 'lib/tty/text/truncation.rb', line 16

def length
  @length
end

#separatorObject (readonly)

Returns the value of attribute separator.



18
19
20
# File 'lib/tty/text/truncation.rb', line 18

def separator
  @separator
end

#textObject (readonly)

Returns the value of attribute text.



14
15
16
# File 'lib/tty/text/truncation.rb', line 14

def text
  @text
end

#trailingObject (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

#truncateObject

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

See Also:



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