Sha256: a62f795e6a09a6f9a9024a525ea5e845c4f6e83db4472cdce6b7dbb65a686c65

Contents?: true

Size: 770 Bytes

Versions: 6

Compression:

Stored size: 770 Bytes

Contents

class Rad::TextUtils::Truncate < Rad::TextUtils::Processor
  def initialize processor, length
    super(processor)
    @length = length
  end
  
  def process str_or_html, env
    str_or_html ||= ""
  
    # Strip from HTML tags
    str_or_html = str_or_html.gsub("<br", " <br").gsub("<p", " <p") # to preserve space in place of <> html elements
    doc = Nokogiri::XML("<div class='root'>#{str_or_html}</div>")
    str = doc.css('.root').first.content

    str = str.gsub(/\s+/, ' ')

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

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
rad_kit-0.0.6 lib/kit/text_utils/truncate.rb
rad_kit-0.0.5 lib/kit/text_utils/truncate.rb
rad_kit-0.0.4 lib/kit/text_utils/truncate.rb
rad_kit-0.0.3 lib/kit/text_utils/truncate.rb
rad_kit-0.0.2 lib/kit/text_utils/truncate.rb
rad_kit-0.0.1 lib/kit/text_utils/truncate.rb