Ruby Command Line RSS Parser

Posted by Tully on Fri 29 November 2013

Task

Create a command line Ruby script for parsing RSS feeds.

Features

  • RSS feed content in various colors for easy viewing.
  • Ability to pull from multiple sources.
  • Option to return only the fields from the RSS you want to display. These fields that are optional are title, description, date, and the link to the post.

Ruby Command Line RSS Reader

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

class WPRSS < Thor
    desc "get URL [--link] [--desc] [--date] [--title=true]", "Parse and display RSS feed to STDOUT"
    option :link, :type => :boolean
    option :desc, :type => :boolean
    option :date, :type => :boolean
    option :title, :type => :boolean, :default => :true

    def get(*urls)
        urls.each do |url|
        uri = URI.parse(url)
        unless uri.kind_of?(URI::HTTP)
            puts "Invalid URL #{url}"
            exit
        end

        content = ""

        open(uri) do |f|
            content = f.read
        end

        rss = RSS::Parser.parse(content, false)
        rss.items.size.times do |i|
            output = []
            output << "#{rss.items[i].title}".colorize(:color => :black, :background => :green)  if options[:title]
            output << "#{rss.items[i].pubDate}" if options[:date]
            output <<  "[#{rss.items[i].link}]".red  if options[:link]
            output << "#{rss.items[i].description}".cyan  if options[:desc]
            output << puts if options.size > 1
            puts output.join("\n")
        end
    end
end

WPRSS.start(ARGV)

Produces

ruby_rss_command_line_parser