Sha256: c1a0c6c5567f51dd1b3dd9105f056de15bd1d20dda0a805c89355733ec4e8a76

Contents?: true

Size: 1.27 KB

Versions: 6

Compression:

Stored size: 1.27 KB

Contents

require 'open-uri'

module Flannel
  class FeedParser
    def initialize cache=nil
      @cache = cache
    end
    
    def sub_feeds(url)
      url = format_url(url)
      get_news(url)
    end
    
    def format_url url
      url.strip!
      url = "http://#{url}" if url[0..6] != "http://"
      url
    end
    
    def get_document url
      URI.parse(url).read
    end
    
    def format_item(link, title)
      "  <li>\n    <a href='#{link}'>#{title}</a>\n  </li>\n"
    end

    def get_news url
      item_string = nil
      item_string = @cache.retrieve(url) if @cache
      
      unless item_string 
	item_string = ""
	doc = get_document(url)
	items = get_items(doc)

	items.each do |item|
	  link = inner_html(item, "link")
	  title = inner_html(item, "title")
	  item_string << format_item(link, title)
	end
	
	@cache.save url, item_string if @cache
      end
      
      item_string
    end
    
    def get_items text
      items = text[/<item>.*<\/item>/mi]
      
      return [] unless items
      
      items.split(/<\/?item>/).reject { |item| /\A\s*\z/ =~ item }
    end
     
    def inner_html text, tag
      regex = Regexp.compile "<#{tag}>(.*)<\/#{tag}>?"

      matches = regex.match text
      return "" unless matches
      
      matches.captures[0]
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
flannel-0.2.13 lib/flannel/feed_parser.rb
flannel-0.2.12 lib/flannel/feed_parser.rb
flannel-0.2.11 lib/flannel/feed_parser.rb
flannel-0.2.10 lib/flannel/feed_parser.rb
flannel-0.2.9 lib/flannel/feed_parser.rb
flannel-0.2.7 lib/flannel/feed_parser.rb