#168 Feed Parsing
Jun 29, 2009 | 10 minutes | Active Record, Plugins
Learn two different techniques for parsing an RSS feed using Feedzirra in this episode!
- Download:
- source codeProject Files in Zip (93.8 KB)
- mp4Full Size H.264 Video (18.8 MB)
- m4vSmaller H.264 Video (11.9 MB)
- webmFull Size VP8 Video (32.1 MB)
- ogvFull Size Theora Video (30.3 MB)
Resources
bash
sudo gem install pauldix-feedzirra script/generate model feed_entry name:string summary:text url:string published_at:datetime guid:string rake db:migrate
config/environment.rb
config.gem "pauldix-feedzirra", :lib => "feedzirra", :source => "http://gems.github.com"
script/console
FeedEntry.update_from_feed("http://feeds.feedburner.com/railscasts") FeedEntry.count
models/feed_entry.rb
class FeedEntry < ActiveRecord::Base def self.update_from_feed(feed_url) feed = Feedzirra::Feed.fetch_and_parse(feed_url) add_entries(feed.entries) end def self.update_from_feed_continuously(feed_url, delay_interval = 15.minutes) feed = Feedzirra::Feed.fetch_and_parse(feed_url) add_entries(feed.entries) loop do sleep delay_interval feed = Feedzirra::Feed.update(feed) add_entries(feed.new_entries) if feed.updated? end end private def self.add_entries(entries) entries.each do |entry| unless exists? :guid => entry.id create!( :name => entry.title, :summary => entry.summary, :url => entry.url, :published_at => entry.published, :guid => entry.id ) end end end end
articles/index.html.erb
<div id="recent_episodes"> <h3>Recent Railscasts Episodes</h3> <ul> <% for entry in FeedEntry.all(:limit => 10, :order => "published_at desc") %> <li><%= link_to h(entry.name), entry.url %></li> <% end %> </ul> </div>