Class: Verse::Truncation
- Inherits:
-
Object
- Object
- Verse::Truncation
- 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
-
#separator ⇒ Object
readonly
Returns the value of attribute separator.
-
#trailing ⇒ Object
readonly
Returns the value of attribute trailing.
Class Method Summary collapse
-
.truncate(text, truncate_at, options = {}) ⇒ Object
Truncate a text at a given length.
Instance Method Summary collapse
-
#initialize(text, options = {}) ⇒ Truncation
constructor
Initialize a Truncation.
-
#truncate(truncate_at = DEFAULT_LENGTH, options = {}) ⇒ Object
Truncate a text at a given length (defualts to 30).
Constructor Details
#initialize(text, options = {}) ⇒ Truncation
Initialize a Truncation
24 25 26 27 28 |
# File 'lib/verse/truncation.rb', line 24 def initialize(text, = {}) @text = text.dup.freeze @separator = .fetch(:separator) { nil } @trailing = .fetch(:trailing) { DEFAULT_TRAILING } end |
Instance Attribute Details
#separator ⇒ Object (readonly)
Returns the value of attribute separator.
10 11 12 |
# File 'lib/verse/truncation.rb', line 10 def separator @separator end |
#trailing ⇒ Object (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
35 36 37 |
# File 'lib/verse/truncation.rb', line 35 def self.truncate(text, truncate_at, = {}) new(text, ).truncate(truncate_at, ) end |
Instance Method Details
#truncate(truncate_at = DEFAULT_LENGTH, options = {}) ⇒ Object
Truncate a text at a given length (defualts to 30)
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, = {}) if display_width(text) <= truncate_at.to_i || truncate_at.to_i.zero? return text.dup end trail = .fetch(:trailing) { trailing } separation = .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 |