Module: NokogiriTruncateHtml::TruncateHtmlHelper
- Defined in:
- lib/nokogiri_truncate_html/truncate_html_helper.rb
Instance Method Summary collapse
-
#truncate_html(input, *args) ⇒ Object
Truncates html respecting tags and html entities.
Instance Method Details
#truncate_html(input, *args) ⇒ Object
Truncates html respecting tags and html entities.
The API is the same as ActionView::Helpers::TextHelper#truncate. It uses Nokogiri and HtmlEntities for entity awareness.
Examples:
truncate_html '<p>Hello <strong>World</strong></p>', :length => 7 # => '<p>Hello <strong>W…</strong></p>'
truncate_html '<p>Hello & Goodbye</p>', :length => 7 # => '<p>Hello &…</p>'
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/nokogiri_truncate_html/truncate_html_helper.rb', line 17 def truncate_html(input, *args) self.document ||= TruncateDocument.new#(TruncateHtmlHelper.flavor) #, length, omission) self.parser ||= Nokogiri::HTML::SAX::Parser.new(document) # support both 2.2 & earlier APIs = args. length = [:length] || args[0] || 30 omission = [:omission] || args[1] || '…' # Adding div around the input is a hack. It gets removed in TruncateDocument. input = "<div>#{input}</div>" self.document.length = length self.document.omission = omission catch(:truncate_finished) do self.parser.parse_memory(input) end self.document.output.html_safe end |