Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

A simple RSS Reader and Podcatcher (See related posts)

Written in Ruby this class reads an RSS feed and downloads the latest enclosure if it exists.

require 'rss/1.0'
require 'rss/2.0'
require 'open-uri'
require 'open-uri'

class Rssreader
  def initialize(url)
    source = url # url or local file
    content = "" # raw content of rss feed will be loaded here
    open(source) do |s| content = s.read end
    @rss = RSS::Parser.parse(content, false)
  end

  # returns the first 3 titles from the rss feed
  def get_summary()
    buffer = '['
    for i in 0..2
      buffer += @rss.items[i.to_i].title + ' | '
    end      
    buffer.slice(0,buffer.length-3) + ']'
  end

  def enclosure?
    @rss.items.to_s.scan('<enclosure').length > 0
  end

  def get_enclosure_url
    enclosure = @rss.items[0].enclosure
    enclosure.url
  end

  def rwget(url, filename)
    file = File.new(filename, 'w')
    file.puts open(url, 'User-Agent' => 'Ruby-wget').read
  end

  def download_enclosure()
    if self.enclosure? then
      enclosure_url = self.get_enclosure_url()
      local_filename = File.basename(enclosure_url)
      #puts local_filename
      if not File.exist?(local_filename) then
        puts 'downloading enclosure ...'
        self.rwget(enclosure_url, local_filename)
        puts 'download completed'
      else
        puts 'enclosure downloaded already'
      end
    end
  end    
end

if __FILE__ == $0
  url = "http://mysite.com/gwd/feed/lugradio.rss"
  rss = Rssreader.new(url)
  puts rss.get_summary()
  rss.download_enclosure()
end

Comments on this post

Hoornet posts on Mar 02, 2008 at 10:02
This is ql!!!
Tnx

You need to create an account or log in to post comments to this site.


Click here to browse all 5147 code snippets

Related Posts