Module: Improvise::Util::StringUtils
- Defined in:
- lib/improvise/util/stringutils.rb
Class Method Summary collapse
-
.truncate(string, truncate_at, options = {}) ⇒ Object
Truncates a given
textafter a givenlengthiftextis longer thanlength:.
Class Method Details
.truncate(string, truncate_at, options = {}) ⇒ Object
Truncates a given text after a given length if text is longer than length:
truncate('Once upon a time in a world far far away', 27)
# => "Once upon a time in a wo..."
Pass a string or regexp :separator to truncate text at a natural break:
truncate('Once upon a time in a world far far away', 27, separator: ' ')
# => "Once upon a time in a..."
truncate('Once upon a time in a world far far away', 27, separator: /\s/)
# => "Once upon a time in a..."
The last characters will be replaced with the :omission string (defaults to “…”) for a total length not exceeding length:
truncate('And they found that many people were sleeping better.', 25, omission: '... (continued)')
# => "And they f... (continued)"
Adapted from Ruby on Rails (released under the MIT license)
24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/improvise/util/stringutils.rb', line 24 def self.truncate(string, truncate_at, = {}) return string.dup unless string.length > truncate_at [:omission] ||= '...' length_with_room_for_omission = truncate_at - [:omission].length stop = if [:separator] string.rindex([:separator], length_with_room_for_omission) || length_with_room_for_omission else length_with_room_for_omission end "#{string[0...stop]}#{[:omission]}" end |