Sha256: 50fe13a81f4bc997a45b989bd620e76c81db9add4021f502799656d3eb7af493

Contents?: true

Size: 1.63 KB

Versions: 18

Compression:

Stored size: 1.63 KB

Contents

require 'nokogiri'

module Awestruct
  module ContextHelper

    def html_to_text(str)
      str.gsub( /<[^>]+>/, '' ).gsub( /&nbsp;/, ' ' )
    end

    def clean_html(str)
      str.gsub( /&nbsp;/, ' ' )
    end

    def without_images(str)
      str.gsub(/<img[^>]+>/,'').gsub(/<a[^>]+>([^<]*)<\/a>/, '\1')
    end

    def close_tags(s)
      stack = []
      s.scan(/<\/?[^>]+>/).each do |tag|
        if tag[1] != '/'
          tag = tag[1..-1].scan(/\w+/).first
          stack = [ tag ] + stack
        else
          tag = tag[2..-1].scan(/\w+/).first
          if stack[0] == tag
            stack = stack.drop(1)
          else
            raise "Malformed HTML expected #{tag[0]} but got #{tag} '#{s}'"
          end
        end
      end
      stack.inject(s) { |memo,tag| memo += "</#{tag}>" }
    end

    def summarize(text, numwords=20, ellipsis='...')
      close_tags(text.split(/ /)[0, numwords].join(' ') + ellipsis)
    end

    def fully_qualify_urls(base_url, text)
      doc = Nokogiri::HTML.fragment( text )

      doc.css( "a" ).each do |a|
        a['href'] = fix_url( base_url, a['href'] ) if a['href']
      end
      doc.css( "link" ).each do |link|
        link['href'] = fix_url( base_url, link['href'] )
      end
      doc.css( "img" ).each do |img|
        img['src'] = fix_url( base_url, img['src'] )
      end

      if RUBY_VERSION.start_with? '1.8'
        doc.to_s
      else
        doc.to_s.tap do |d| 
          d.force_encoding(text.encoding) if d.encoding != text.encoding 
        end 
      end
    end

    def fix_url(base_url, url)
      return url unless ( url =~ /^\// )
      "#{base_url}#{url}"
    end
  end

end

Version data entries

18 entries across 18 versions & 1 rubygems

Version Path
awestruct-0.5.6.beta3 lib/awestruct/context_helper.rb
awestruct-0.5.6.beta2 lib/awestruct/context_helper.rb
awestruct-0.5.6.beta lib/awestruct/context_helper.rb
awestruct-0.5.5 lib/awestruct/context_helper.rb
awestruct-0.5.4.2 lib/awestruct/context_helper.rb
awestruct-0.5.4.1 lib/awestruct/context_helper.rb
awestruct-0.5.4 lib/awestruct/context_helper.rb
awestruct-0.5.4.rc3 lib/awestruct/context_helper.rb
awestruct-0.5.4.rc2 lib/awestruct/context_helper.rb
awestruct-0.5.4.rc lib/awestruct/context_helper.rb
awestruct-0.5.4.beta1 lib/awestruct/context_helper.rb
awestruct-0.5.3 lib/awestruct/context_helper.rb
awestruct-0.5.2.1 lib/awestruct/context_helper.rb
awestruct-0.5.2 lib/awestruct/context_helper.rb
awestruct-0.5.1 lib/awestruct/context_helper.rb
awestruct-0.5.1a lib/awestruct/context_helper.rb
awestruct-0.5.0 lib/awestruct/context_helper.rb
awestruct-0.5.0.cr lib/awestruct/context_helper.rb