Benjamin Curtis

Speculations on Web Development

Republish RSS Feeds With Rails

| Comments

If you’d like to repurpose RSS feeds for display on your site, FeedTools is a great library for fetching and parsing feeds. FeedTools also makes it easy to cache the results of parsing a feed.

In the music store that I’m creating, products can be associated with artists, and those artists often have blogs or other feeds. We can use those feeds to pull info about the artist into the view when displaying a product by the artist. Here’s an example of parsing a feed and displaying the feed items in a view.

The table: create_table "cached_feeds" do |t| t.column "href", :string t.column "title", :string t.column "link", :string t.column "feed_data", :text t.column "feed_data_type", :string t.column "http_headers", :text t.column "last_retrieved", :datetime end

The helper: def parse_feed(url) return if url.blank? FeedTools.configurations[:feed_cache] = "FeedTools::DatabaseFeedCache" FeedTools::Feed.open(url) end

And the view: < % if @product.artist && feed = parse_feed(@product.artist.feed_url) %>

Recent news for < %=h @product.artist.name %>

    < % feed.items[0..4].each do |item| %>
  • < %= link_to_if item.link, item.title, item.link %> - < %= item.time %>
  • < % end %>
< % end %>
And you’re done. :)

Comments