Class: Nokogiri::XML::Text

Inherits:
Object
  • Object
show all
Defined in:
lib/html_truncator.rb

Instance Method Summary collapse

Instance Method Details

#truncate(max, opts) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/html_truncator.rb', line 74

def truncate(max, opts)
  if opts[:length_in_chars]
    count = content.length
    return [to_xhtml, count, opts] if count <= max && max > 0
    words = content.scan(/[[:space:]]*[[:graph:]]+/)
    if words.size > 1
      words.inject('') do |string, word|
        if string.length + word.length > max
          txt = dup
          txt.content = string
          return [txt.to_xhtml, count, opts]
        end
        string + word
      end
    end
    txt = dup
    txt.content = content.slice(0, max)
    [txt.to_xhtml, count, opts]
  else
    words = to_xhtml.scan(/[[:space:]]*[[:graph:]]+/)
    count = words.length
    return [to_xhtml, count, opts] if count <= max && max > 0
    [words.slice(0, max).join, count, opts]
  end
end