module Doing::StringTruncate

String truncation

Public Instance Methods

trunc(len, ellipsis: '...') click to toggle source

Truncate to nearest word

@param len The length

# File lib/doing/string/truncate.rb, line 13
def trunc(len, ellipsis: '...')
  return self if length <= len

  total = 0
  res = []

  split(/ /).each do |word|
    break if total + 1 + word.length > len

    total += 1 + word.length
    res.push(word)
  end
  res.join(' ') + ellipsis
end
trunc!(len, ellipsis: '...') click to toggle source
# File lib/doing/string/truncate.rb, line 28
def trunc!(len, ellipsis: '...')
  replace trunc(len, ellipsis: ellipsis)
end
truncend(len, ellipsis: '...') click to toggle source

Truncate from middle to end at nearest word

@param len The length

# File lib/doing/string/truncate.rb, line 37
def truncend(len, ellipsis: '...')
  return self if length <= len

  total = 0
  res = []

  split(/ /).reverse.each do |word|
    break if total + 1 + word.length > len

    total += 1 + word.length
    res.unshift(word)
  end
  ellipsis + res.join(' ')
end
truncend!(len, ellipsis: '...') click to toggle source
# File lib/doing/string/truncate.rb, line 52
def truncend!(len, ellipsis: '...')
  replace truncend(len, ellipsis: ellipsis)
end
truncmiddle(len, ellipsis: '...') click to toggle source

Truncate string in the middle, separating at nearest word

@param len The length @param ellipsis The ellipsis

# File lib/doing/string/truncate.rb, line 62
def truncmiddle(len, ellipsis: '...')
  return self if length <= len
  len -= (ellipsis.length / 2).to_i
  half = (len / 2).to_i
  start = trunc(half, ellipsis: ellipsis)
  finish = truncend(half, ellipsis: '')
  start + finish
end
truncmiddle!(len, ellipsis: '...') click to toggle source
# File lib/doing/string/truncate.rb, line 71
def truncmiddle!(len, ellipsis: '...')
  replace truncmiddle(len, ellipsis: ellipsis)
end