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

'...'
SEPARATOR =

natural break point

' '

Class Method Summary collapse

Class Method Details

.first_line(message) ⇒ Object


60
61
62
# File 'lib/yarr/message/truncator.rb', line 60

def first_line(message)
  message.lines.then { |lines| [lines.count > 1, lines.first.strip] }
end

.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.


50
51
52
53
54
55
56
# File 'lib/yarr/message/truncator.rb', line 50

def split_point(message, omission, suffix)
  split_length = MAX_LENGTH - omission.length - suffix.length  # If the message doesn't end with separator but shorter than allowed
  # length we don't want to chop of the last section of it

  message += SEPARATOR
  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


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

def truncate(message,
             omission: OMISSION,
             suffix: '')
  multiline, first_line = first_line(message)
  suffixed = first_line + suffix
  return suffixed if suffixed.length <= MAX_LENGTH && ! multiline

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