Sha256: 94496085a3fa7a7b84ce3b8ede73640678aa314e3406d4deb689fa3a3a7b4671

Contents?: true

Size: 1.88 KB

Versions: 28

Compression:

Stored size: 1.88 KB

Contents

class Card
  class Content
    # tools for truncating content
    module Truncate
      ELLIPSES_HTML = '<span class="closed-content-ellipses">...</span>'.freeze

      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

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

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

      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

      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
    end
  end
end

Version data entries

28 entries across 28 versions & 1 rubygems

Version Path
card-1.96.8 lib/card/content/truncate.rb
card-1.96.7 lib/card/content/truncate.rb
card-1.96.6 lib/card/content/truncate.rb
card-1.96.5 lib/card/content/truncate.rb
card-1.96.4 lib/card/content/truncate.rb
card-1.96.3 lib/card/content/truncate.rb
card-1.96.2 lib/card/content/truncate.rb
card-1.96.1 lib/card/content/truncate.rb
card-1.96.0 lib/card/content/truncate.rb
card-1.95.3 lib/card/content/truncate.rb
card-1.95.2 lib/card/content/truncate.rb
card-1.95.1 lib/card/content/truncate.rb
card-1.95.0 lib/card/content/truncate.rb
card-1.94.1 lib/card/content/truncate.rb
card-1.94.0 lib/card/content/truncate.rb
card-1.93.13 lib/card/content/truncate.rb
card-1.93.12 lib/card/content/truncate.rb
card-1.93.11 lib/card/content/truncate.rb
card-1.93.10 lib/card/content/truncate.rb
card-1.93.9 lib/card/content/truncate.rb