Module: Card::Content::Truncate

Included in:
Card::Content
Defined in:
lib/card/content/truncate.rb

Overview

tools for truncating content

Constant Summary collapse

ELLIPSES_HTML =
'<span class="closed-content-ellipses">...</span>'.freeze

Instance Method Summary collapse

Instance Method Details

#close_tags(wordstring) ⇒ Object



28
29
30
31
32
# File 'lib/card/content/truncate.rb', line 28

def close_tags wordstring
  tags = find_tags wordstring
  tags.each { |t| wordstring += "</#{t}>" }
  wordstring
end

#find_tags(wordstring) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/card/content/truncate.rb', line 42

def find_tags wordstring
  tags = []

  # match tags with or without self closing (ie. <foo />)
  wordstring.scan(%r{\<([^\>\s/]+)[^\>]*?\>}).each do |t|
    tags.unshift(t[0])
  end
  # match tags with self closing and mark them as closed
  wordstring.scan(%r{\<([^\>\s/]+)[^\>]*?/\>}).each do |t|
    next unless (x = tags.index(t[0]))

    tags.slice!(x)
  end
  # match close tags
  wordstring.scan(%r{\</([^\>\s/]+)[^\>]*?\>}).each do |t|
    next unless (x = tags.rindex(t[0]))

    tags.slice!(x)
  end
  tags
end

#polish(wordstring) ⇒ Object



34
35
36
37
38
39
40
# File 'lib/card/content/truncate.rb', line 34

def polish wordstring
  wordstring.gsub! %r{<[/]?br[\s/]*>}, " "
  # Also a hack -- get rid of <br>'s -- they make line view ugly.
  wordstring.gsub! %r{<[/]?p[^>]*>}, " "
  ## Also a hack -- get rid of <br>'s -- they make line view ugly.
  wordstring
end

#smart_truncate(input, words = 25) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
# File 'lib/card/content/truncate.rb', line 7

def smart_truncate input, words=25
  return if input.nil?

  truncated, wordstring = truncate input, words
  # nuke partial tags at end of snippet
  wordstring.gsub!(/(<[^\>]+)$/, "")
  wordstring = close_tags wordstring
  wordstring += ELLIPSES_HTML if truncated
  # wordstring += '...' if wordlist.length > l
  polish wordstring
end

#truncate(input, words) ⇒ Object



19
20
21
22
23
24
25
26
# File 'lib/card/content/truncate.rb', line 19

def truncate input, words
  wordlist = input.to_s.split
  l = words.to_i - 1
  l = 0 if l.negative?
  truncating = wordlist.length > l
  wordstring = truncating ? wordlist[0..l].join(" ") : input.to_s
  [truncating, wordstring]
end