Class: Verse::Truncation

Inherits:
Object
  • Object
show all
Defined in:
lib/verse/truncation.rb

Overview

A class responsible for text truncation operations

Constant Summary collapse

DEFAULT_TRAILING =
''.freeze
DEFAULT_LENGTH =
30

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(text, options = {}) ⇒ Truncation

Initialize a Truncation

Parameters:

  • text (String)

    the text to be truncated

  • options (Hash) (defaults to: {})

    @option options [Symbol] :separator the character for splitting words @option options [Symbol] :trailing the character for ending sentence



24
25
26
27
28
# File 'lib/verse/truncation.rb', line 24

def initialize(text, options = {})
  @text      = text.dup.freeze
  @separator = options.fetch(:separator) { nil }
  @trailing  = options.fetch(:trailing) { DEFAULT_TRAILING }
end

Instance Attribute Details

#separatorObject (readonly)

Returns the value of attribute separator.



10
11
12
# File 'lib/verse/truncation.rb', line 10

def separator
  @separator
end

#trailingObject (readonly)

Returns the value of attribute trailing.



12
13
14
# File 'lib/verse/truncation.rb', line 12

def trailing
  @trailing
end

Class Method Details

.truncate(text, truncate_at, options = {}) ⇒ Object

Truncate a text at a given length

See Also:



35
36
37
# File 'lib/verse/truncation.rb', line 35

def self.truncate(text, truncate_at, options = {})
  new(text, options).truncate(truncate_at, options)
end

Instance Method Details

#truncate(truncate_at = DEFAULT_LENGTH, options = {}) ⇒ Object

Truncate a text at a given length (defualts to 30)

Examples:

truncation = Verse::Truncation.new
  "The sovereignest thing on earth is parmacetti for an inward bruise."

truncation.truncate
# => "The sovereignest thing on ear…"

truncate(20)
# => "The sovereignest th…"

truncate(20, separator: ' ' )
# => "The sovereignest…"

truncate(40, trailing: '... (see more)' )
# => "The sovereignest thing on... (see more)"


58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/verse/truncation.rb', line 58

def truncate(truncate_at = DEFAULT_LENGTH, options = {})
  if display_width(text) <= truncate_at.to_i || truncate_at.to_i.zero?
    return text.dup
  end
  trail      = options.fetch(:trailing) { trailing }
  separation = options.fetch(:separator) { separator }
  width      = display_width(text)
  sanitized_text = Sanitizer.sanitize(text)

  return text if width <= truncate_at

  length_without_trailing = truncate_at - display_width(trail)
  chars = to_chars(sanitized_text).to_a
  stop  = chars[0, length_without_trailing].rindex(separation)
  slice_length = stop || length_without_trailing
  sliced_chars = chars[0, slice_length]
  original_chars = to_chars(text).to_a[0, 3 * slice_length]
  shorten(original_chars, sliced_chars, length_without_trailing).join + trail
end