Module: Yarr::Message::Truncator

Included in:
Bot
Defined in:
lib/yarr/message/truncator.rb

Overview

Flood protection.

Constant Summary collapse

MAX_LENGTH =

max message length.

160
OMISSION =

use … if truncated

'...'.freeze
SEPARATOR =

natural break point

' '.freeze

Class Method Summary collapse

Class Method Details

.split_point(message, omission, suffix) ⇒ 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.


48
49
50
51
# File 'lib/yarr/message/truncator.rb', line 48

def split_point(message, omission, suffix)
  split_length = MAX_LENGTH - omission.length - suffix.length
  message.rindex(SEPARATOR, split_length) || split_length
end

.truncate(message, omission: OMISSION, suffix: '') ⇒ String

Truncates the given string to the predefined maximum size.

Examples:

Truncator.truncate('Lorem ipsum dolor sit amet, consectetur' \
                   ' adipisicing elit, sed do eiusmod tempor' \
                   ' incididunt ut labore et dolore magna aliqua.' \
                   ' Ut enim ad minim veniam, quis nostrud' \
                   ' exercitation ullamco laboris nisi ut aliquip ' \
                   ' ex ea commodo consequat. Duis aute irure ' \
                   ' dolor in reprehenderit in voluptate velit ' \
                   ' esse cillum dolore eu fugiat nulla pariatur. ' \
                   ' Excepteur sint occaecat cupidatat non ' \
                   ' proident, sunt in culpa qui officia deserunt' \
                   ' mollit anim id est laborum.')# => "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed" \
# "do eiusmod tempor incididunt ut labore et dolore magna aliqua." \
# "Ut enim ad minim veniam, quis..."

Parameters:

  • message (String)

    the string to truncate

  • omission (String) (defaults to: OMISSION)

    The string that indicates the message was truncated

  • suffix (String) (defaults to: '')

    a suffix that's always appended after the string regardless of whether it was truncated or not. The truncation length however takes it into account.

Returns:

  • (String)

    the truncated message


32
33
34
35
36
37
38
39
40
41
# File 'lib/yarr/message/truncator.rb', line 32

def truncate(message,
             omission: OMISSION,
             suffix: '')
  message = message.lines.first.strip
  suffixed = message + suffix
  return suffixed if suffixed.length <= MAX_LENGTH

  split_point = split_point(message, omission, suffix)
  "#{message[0, split_point]}#{omission}#{suffix}"
end