Skip to content

Instantly share code, notes, and snippets.

@jdm
Created August 24, 2009 18:45
Show Gist options
  • Save jdm/174058 to your computer and use it in GitHub Desktop.
Save jdm/174058 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'hpricot'
module HpricotTruncator
module NodeWithChildren
def truncate(max_length)
return self if inner_text.length <= max_length
truncated_node = self.dup
truncated_node.children = []
each_child do |node|
remaining_length = max_length - truncated_node.inner_text.length
break if remaining_length == 0
truncated_node.children << node.truncate(remaining_length)
end
truncated_node
end
end
end
Hpricot::Doc.send(:include, HpricotTruncator::NodeWithChildren)
doc = Hpricot("Pākistānī, Hindustāni")
puts doc.truncate(5).inner_html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment