Module: SmartExcerpt

Extended by:
Util
Defined in:
lib/smart_excerpt.rb,
lib/smart_excerpt/util.rb,
lib/smart_excerpt/helper.rb,
lib/smart_excerpt/version.rb

Defined Under Namespace

Modules: ClassMethods, Util Classes: Helper

Constant Summary collapse

VERSION =
"0.2.0"
@@h =
Helper.new
@@he =
HTMLEntities.new

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Util

decode, decode_and_strip, encode, simple_format, strip_tags, truncate

Class Method Details

.included(base) ⇒ Object



14
15
16
# File 'lib/smart_excerpt.rb', line 14

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

Instance Method Details

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



19
20
21
22
23
24
25
26
27
28
29
30
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
57
58
59
60
61
62
63
64
# File 'lib/smart_excerpt.rb', line 19

def smart_truncate(obj, base_field, excerpt_field, words)
  trust_multiplier = 1.2
  if words.is_a?(Hash) && words[:trust_multiplier]
    trust_multiplier = words[:trust_multiplier]
  end

  if obj.send(excerpt_field).blank?
    tx = obj.send(base_field)
  else
    tx = obj.send(excerpt_field)
    if words.is_a?(Numeric)
      words *= trust_multiplier
    elsif words.is_a?(Hash)
      if words[:trust_excerpts]
        words = {words: Float::INFINITY}
      else
        words = Hash[words.map {|k, v| [k, v.is_a?(Numeric) ? (v * trust_multiplier).to_i : v] }]
      end
    end
  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
    unless options[:keep_headers]
      tx = tx.gsub(/<h\d[^>]*?>(.*?)<\/h\d>/mi, '')
    end
    unless options[:keep_newlines]
      tx = tx.gsub("\n", ' ').gsub("\r", '').gsub("\t", '').strip
    end
    tx = @@he.decode(tx)
    unless options[:keep_html]
      tx = @@h.strip_tags(tx)
    end
    @@h.smart_truncate(tx, options)
  end
end