Class: TTY::Table::Operation::Truncation

Inherits:
Object
  • Object
show all
Includes:
Unicode
Defined in:
lib/tty/table/operation/truncation.rb

Overview

A class responsible for shortening text.

Instance Method Summary collapse

Methods included from Unicode

#as_unicode, #clean_utf8, #utf8?

Instance Method Details

#truncate(string, width, trailing = '…') ⇒ String

Shorten given string with traling character.

Parameters:

  • string (String)

    the string to truncate

  • width (Integer)

    the maximum width

  • trailing (String) (defaults to: '…')

    the trailing character

Returns:

  • (String)


23
24
25
26
27
28
29
30
31
32
33
# File 'lib/tty/table/operation/truncation.rb', line 23

def truncate(string, width, trailing = '')
  as_unicode do
    chars = string.chars.to_a
    if chars.length < width
      chars.join
    else
      traling_size = trailing.chars.to_a.size
      ( chars[0, width - traling_size].join ) + trailing
    end
  end
end