Class: Lightning::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/lightning/parser.rb

Class Method Summary collapse

Class Method Details

.parse(opts = {}) ⇒ Object

pass :feed for the feed url or file location - required pass :posts for the number of posts to return - optional returns an array of Lightning::Post objects



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
# File 'lib/lightning/parser.rb', line 7

def parse(opts={})
  raise "need to provide a feed url or file for this to work" unless opts[:feed]
  posts = []
  feed = opts[:feed]
  unless File.exists?(feed)
    feed = "http://" + feed unless feed.include?("http://")
  end  
  # TODO [tm] handle exceptions and errors
  # handle if file is not found - don't try to add http - remove this piece probably
  doc = XML::Parser.file(feed).parse
  items = doc.find("//*[local-name()='item']").to_a
  items = items[0, (opts[:posts] > items.length ? items.length : opts[:posts])] if opts[:posts]
  items.each do |item|
    desc = item.find('description').first.content            
    title = item.find('title').first.content
    link = item.find('link').first.content
    pub_date = Time.parse(item.find('pubDate').first.content)
    thumbnail = item.find('media:thumbnail').first.attributes[:url] if item.find('media:thumbnail').first  
    player = item.find('media:player').first.attributes[:url] if item.find('media:player').first  
    posts << Lightning::Post.new( :title=>title, 
                                  :pub_date    =>  pub_date, 
                                  :link        => link, 
                                  :description => desc, 
                                  :feed        =>  feed, 
                                  :thumbnail   =>  thumbnail,
                                  :player      => player ) 
  end
  return posts
end