app/helpers/application_helper.rb
# HTML truncate for valid HTML, requires REXML::Parsers::PullParser
HTML truncate for valid HTML, requires REXML::Parsers::PullParser
HTML truncate for valid HTML requires REXML :: Parsers :: PullParser
def truncate_well_formed_html(input, len = 30, extension = "...")
    def attrs_to_s(attrs)
      return '' if attrs.empty?
      attrs.to_a.map { |attr| %{#{attr[0]}="#{attr[1]}"} }.join(' ')
    end
    p = REXML::Parsers::PullParser.new(input)
      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
      end
    end
    tags.reverse.each do |tag|
      results << "</#{tag}>"
    end
    (results.to_s + (input.length > len ? extension : '')).html_safe
  end
def truncate_well_formed_html ( input , len = 30 , extension = "..." ) def attrs_to_s ( attrs ) return '' if attrs . empty? attrs . to_a . map { | attr | %{#{attr[0]}="#{attr[1]}"} } . join ( ' ' ) end p = REXML :: Parsers :: PullParser . new ( input ) 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 end end tags . reverse . each do | tag | results << "</#{tag}>" end ( results . to_s + ( input . length > len ? extension : '' ) ) . html_safe end
HTML truncate for valid HTML, requires REXML::Parsers::PullParser
HTML truncate for valid HTML requires REXML :: Parsers :: PullParser
input
<not_specific>
len
<not_specific>
extension
<not_specific>