Class: SmartExcerpt::Helper

Inherits:
Object
  • Object
show all
Includes:
ActionView::Helpers::TextHelper
Defined in:
lib/smart_excerpt/helper.rb

Instance Method Summary collapse

Instance Method Details

#smart_truncate(s, opts = {}) ⇒ Object



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/) # or /[ ]+/ to only split on spaces
  r = a[0...n].join(' ') + (a.size > n ? '...' : '')

  # replace   with regular spaces
  r.gsub!(' ', ' ')

  # strip newlines
  r = r.strip.gsub("\r", '').gsub("\n", ' ')

  r.gsub(/\s+/, ' ')
end