Sha256: 253e2df709dc08887c11b368cd421c08be12d0cf7896b8ea222715118f352d50

Contents?: true

Size: 746 Bytes

Versions: 2

Compression:

Stored size: 746 Bytes

Contents

class TextUtils::Truncate < TextUtils::Processor
  def initialize processor, length
    super processor
    @length = length
  end

  def call data, env
    data ||= ""

    # strip from HTML tags
    data = data.gsub("<br", " <br").gsub("<p", " <p") # to preserve space in place of <> html elements
    doc = Nokogiri::XML("<div class='root'>#{data}</div>")
    data = doc.css('.root').first.content

    # remove clear space
    data = data.gsub(/\s+/, ' ')

    # truncate with no broken words
    data = if data.length >= @length
      shortened = data[0, @length]
      splitted = shortened.split(/\s/)
      words = splitted.length
      splitted[0, words-1].join(" ") + ' ...'
    else
      data
    end

    call_next data, env
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rad_kit-0.0.10 lib/text_utils/truncate.rb
rad_kit-0.0.9 lib/text_utils/truncate.rb