Sha256: 429a0dafc73a66d8855b5644ca734d1980ba97cb626025492170693b0b990c75

Contents?: true

Size: 1.59 KB

Versions: 41

Compression:

Stored size: 1.59 KB

Contents

# frozen_string_literal: true

module Doing
  ##
  ## String truncation
  ##
  module StringTruncate
    ##
    ## Truncate to nearest word
    ##
    ## @param      len   The length
    ##
    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

    def trunc!(len, ellipsis: '...')
      replace trunc(len, ellipsis: ellipsis)
    end

    ##
    ## Truncate from middle to end at nearest word
    ##
    ## @param      len   The length
    ##
    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

    def truncend!(len, ellipsis: '...')
      replace truncend(len, ellipsis: ellipsis)
    end

    ##
    ## Truncate string in the middle, separating at nearest word
    ##
    ## @param      len       The length
    ## @param      ellipsis  The ellipsis
    ##
    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

    def truncmiddle!(len, ellipsis: '...')
      replace truncmiddle(len, ellipsis: ellipsis)
    end
  end
end

Version data entries

41 entries across 41 versions & 1 rubygems

Version Path
doing-2.1.88 lib/doing/string/truncate.rb
doing-2.1.87 lib/doing/string/truncate.rb
doing-2.1.86 lib/doing/string/truncate.rb
doing-2.1.85 lib/doing/string/truncate.rb
doing-2.1.84 lib/doing/string/truncate.rb
doing-2.1.83 lib/doing/string/truncate.rb
doing-2.1.82 lib/doing/string/truncate.rb
doing-2.1.81 lib/doing/string/truncate.rb
doing-2.1.80 lib/doing/string/truncate.rb
doing-2.1.79 lib/doing/string/truncate.rb
doing-2.1.78 lib/doing/string/truncate.rb
doing-2.1.77 lib/doing/string/truncate.rb
doing-2.1.76 lib/doing/string/truncate.rb
doing-2.1.75 lib/doing/string/truncate.rb
doing-2.1.74 lib/doing/string/truncate.rb
doing-2.1.73 lib/doing/string/truncate.rb
doing-2.1.72 lib/doing/string/truncate.rb
doing-2.1.69 lib/doing/string/truncate.rb
doing-2.1.68 lib/doing/string/truncate.rb
doing-2.1.66 lib/doing/string/truncate.rb