5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
# File 'lib/smart_excerpt/helper.rb', line 5
def smart_truncate(s, opts = {})
return '' if s.blank?
opts = {words: 25}.merge(opts)
if opts[:sentences]
return s.split(/\.(\s|$)+/).delete_if {|s| s.blank? }[0, opts[:sentences]].map{|s| s.strip}.join('. ') + '.'
end
if opts[:letters]
return truncate(s, length: opts[:letters], separator: ' ', omission: '...')
end
n = opts[:words]
if n === Float::INFINITY
return s
end
a = s.split(/\s/) r = a[0...n].join(' ') + (a.size > n ? '...' : '')
r.gsub!(' ', ' ')
r = r.strip.gsub("\r", '').gsub("\n", ' ')
r.gsub(/\s+/, ' ')
end
|