module TruncateHTML

Taken and modified from madebydna.com/all/code/2010/06/04/ruby-helper-to-cleanly-truncate-html.html MIT license

Public Class Methods

truncate_at_length(text, max_length, ellipsis = '...') click to toggle source
# File lib/middleman-blog/truncate_html.rb, line 16
def self.truncate_at_length(text, max_length, ellipsis = '...')
  ellipsis_length = ellipsis.length
  text = text.encode('UTF-8') if text.respond_to?(:encode)
  doc = Nokogiri::HTML::DocumentFragment.parse text
  content_length = doc.inner_text.length
  actual_length = max_length - ellipsis_length
  if content_length > actual_length
    doc.truncate(actual_length, ellipsis).inner_html
  else
    text
  end
end
truncate_at_separator(text, separator) click to toggle source
# File lib/middleman-blog/truncate_html.rb, line 10
def self.truncate_at_separator(text, separator)
  text = text.encode('UTF-8') if text.respond_to?(:encode)
  doc = Nokogiri::HTML::DocumentFragment.parse text.split(separator).first
  doc.inner_html
end