Module: TruncateHTML
- Defined in:
- lib/middleman-blog/truncate_html.rb
Overview
Taken and modified from madebydna.com/all/code/2010/06/04/ruby-helper-to-cleanly-truncate-html.html MIT license
Class Method Summary collapse
- .truncate_at_length(text, max_length, ellipsis = '...') ⇒ Object
- .truncate_at_separator(text, separator) ⇒ Object
Class Method Details
.truncate_at_length(text, max_length, ellipsis = '...') ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/middleman-blog/truncate_html.rb', line 18 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) ⇒ Object
12 13 14 15 16 |
# File 'lib/middleman-blog/truncate_html.rb', line 12 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 |