Created
August 24, 2009 18:45
-
-
Save jdm/174058 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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