Module: SmartExcerpt

Defined in:
lib/smart_excerpt.rb

Defined Under Namespace

Modules: ClassMethods, InstanceMethods Classes: Helper

Constant Summary collapse

@@h =
Helper.new
@@he =
HTMLEntities.new

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.decode(str) ⇒ Object



63
64
65
# File 'lib/smart_excerpt.rb', line 63

def self.decode(str)
  @@he.decode(str)
end

.decode_and_strip(str) ⇒ Object



75
76
77
# File 'lib/smart_excerpt.rb', line 75

def self.decode_and_strip(str)
  self.strip_tags(self.decode(str))
end

.encode(str) ⇒ Object



67
68
69
# File 'lib/smart_excerpt.rb', line 67

def self.encode(str)
  @@he.encode(str)
end

.included(base) ⇒ Object



58
59
60
61
# File 'lib/smart_excerpt.rb', line 58

def self.included(base)
  base.send(:extend, ClassMethods)
  base.send(:include, InstanceMethods)
end

.strip_tags(str) ⇒ Object



71
72
73
# File 'lib/smart_excerpt.rb', line 71

def self.strip_tags(str)
  @@h.strip_tags(str)
end

.truncate(str, opts = {}) ⇒ Object



79
80
81
82
83
84
85
# File 'lib/smart_excerpt.rb', line 79

def self.truncate(str, opts = {})
  return '' if str.blank?
  tx = str.gsub(/<h\d[^>]*?>(.*)<\/h\d>/mi, '').gsub("\n", ' ').gsub("\r", '').gsub("\t", '').strip
  tx = @@he.decode(tx)
  tx = @@h.strip_tags(tx)
  @@h.smart_truncate(tx, opts)
end

Instance Method Details

#smart_truncate(obj, base_field, excerpt_field, words) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/smart_excerpt.rb', line 31

def smart_truncate(obj, base_field, excerpt_field, words)
  if obj.send(excerpt_field).blank?
    tx = obj.send(base_field)
  else
    tx = obj.send(excerpt_field)
    words *= 1.2 if words.is_a?(Fixnum)
  end
  
  if words.is_a?(Numeric)
    options = {words: words.to_i}
  elsif words.is_a?(Hash)
    options = words
  else
    raise 'bad parameter for get_excerpt'
  end

  if tx.blank?
    ''
  else
    # kill headers and newlines
    tx = tx.gsub(/<h\d[^>]*?>(.*?)<\/h\d>/mi, '').gsub("\n", ' ').gsub("\r", '').gsub("\t", '').strip
    tx = @@he.decode(tx)
    tx = @@h.strip_tags(tx)
    @@h.smart_truncate(tx, options)
  end
end