Created
December 9, 2008 10:48
-
-
Save tomtaylor/33876 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
| class String | |
| require 'rexml/parsers/pullparser' | |
| def truncate_html(len = 30) | |
| p = REXML::Parsers::PullParser.new(self) | |
| tags = [] | |
| new_len = len | |
| results = '' | |
| while p.has_next? && new_len > 0 | |
| p_e = p.pull | |
| case p_e.event_type | |
| when :start_element | |
| tags.push p_e[0] | |
| results << "<#{tags.last} #{attrs_to_s(p_e[1])}>" | |
| when :end_element | |
| results << "</#{tags.pop}>" | |
| when :text | |
| results << p_e[0].first(new_len) | |
| new_len -= p_e[0].length | |
| if new_len < 0 | |
| results << '…' | |
| end | |
| else | |
| results << "<!-- #{p_e.inspect} -->" | |
| end | |
| end | |
| tags.reverse.each do |tag| | |
| results << "</#{tag}>" | |
| end | |
| results | |
| end | |
| private | |
| def attrs_to_s(attrs) | |
| if attrs.empty? | |
| '' | |
| else | |
| attrs.to_a.map { |attr| %{#{attr[0]}="#{attr[1]}"} }.join(' ') | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment