Class: TextUtils::Truncate

Inherits:
Processor show all
Defined in:
lib/text_utils/truncate.rb

Instance Method Summary collapse

Constructor Details

#initialize(processor, length) ⇒ Truncate

Returns a new instance of Truncate.



2
3
4
5
# File 'lib/text_utils/truncate.rb', line 2

def initialize processor, length
  super processor
  @length = length
end

Instance Method Details

#call(data, env) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/text_utils/truncate.rb', line 7

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