feed_handler.rb
1014 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
require 'feedparser'
require 'open-uri'
class FeedHandler
  def parse(content)
    raise FeedHandler::ParseError, "Content is nil" if content.nil?
    begin
      return FeedParser::Feed::new(content)
    rescue Exception => ex
      raise FeedHandler::ParseError, ex.to_s
    end
  end
  def fetch(address)
    begin
      content = ""
      open(address) do |s| content = s.read end
      return content
    rescue Exception => ex
      raise FeedHandler::FetchError, ex.to_s
    end
  end
  def process(container)
    container.class.transaction do
      container.clear
      content = fetch(container.address)
      container.fetched_at = Time.now
      parsed_feed = parse(content)
      container.feed_title = parsed_feed.title
      parsed_feed.items[0..container.limit-1].reverse.each do |item|
        container.add_item(item.title, item.link, item.date, item.content)
      end
      container.finish_fetch
    end
  end
  class ParseError < Exception; end
  class FetchError < Exception; end
end