Sha256: 795e0fa3a32dc9ee345636506a0f0bde9538db7386ed2ed64d140e675ffe5813

Contents?: true

Size: 1.58 KB

Versions: 14

Compression:

Stored size: 1.58 KB

Contents

# frozen_string_literal: true

module Doing
  ##
  ## String truncation
  ##
  class ::String
    ##
    ## 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

14 entries across 14 versions & 1 rubygems

Version Path
doing-2.1.40 lib/doing/string/truncate.rb
doing-2.1.39 lib/doing/string/truncate.rb
doing-2.1.38 lib/doing/string/truncate.rb
doing-2.1.37 lib/doing/string/truncate.rb
doing-2.1.36 lib/doing/string/truncate.rb
doing-2.1.35 lib/doing/string/truncate.rb
doing-2.1.34 lib/doing/string/truncate.rb
doing-2.1.33 lib/doing/string/truncate.rb
doing-2.1.32 lib/doing/string/truncate.rb
doing-2.1.31pre lib/doing/string/truncate.rb
doing-2.1.30 lib/doing/string/truncate.rb
doing-2.1.29 lib/doing/string/truncate.rb
doing-2.1.28 lib/doing/string/truncate.rb
doing-2.1.27 lib/doing/string/truncate.rb