Created
November 10, 2011 15:16
-
-
Save slhck/1355086 to your computer and use it in GitHub Desktop.
A simple RSS/Atom reader for Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# rss-reader.rb | |
# Author: Werner Robitza | |
# Synopsis: A basic console RSS News Feed reader | |
# Usage: rss-reader.rb <url> <granularity> | |
# <url> being the URL of the RSS news feed | |
# <granularity> is one of: short | medium | full | |
require 'open-uri' | |
require 'nokogiri' | |
require 'pp' | |
def show_usage | |
puts "Usage: rss-reader.rb <url> <granularity>" | |
puts "<url> being the URL of the RSS news feed" | |
puts "<granularity> is one of: short | medium | full" | |
exit | |
end | |
# ----------------------------------------------------------------------------- | |
show_usage if ARGV.size != 2 | |
# assign parameters | |
remote_uri, @verbosity = ARGV | |
# check if right usage of parameters | |
usage if not ["short", "medium", "full"].include? @verbosity | |
begin | |
@doc = Nokogiri::HTML(open(remote_uri)) | |
@doc.remove_namespaces! | |
rescue | |
puts "Could not open URI, aborting." | |
exit | |
end | |
# let's find out if this is RSS or Atom | |
@type = :atom if @doc.root.xpath("body/feed").size == 1 | |
@type = :rss if @doc.root.xpath("body/rss").size == 1 | |
# print the title | |
puts @doc.xpath("//channel/title").text if @type == :rss | |
puts @doc.xpath("//feed/title").text if @type == :atom | |
80.times { print "=" } and print "\n" | |
# print each item | |
item_xpath = "//channel/item" if @type == :rss | |
item_xpath = "//feed/entry" if @type == :atom | |
@doc.xpath(item_xpath).each do |item| | |
puts item.xpath("title").text | |
if @verbosity == "medium" or @verbosity == "full" | |
puts item.xpath("pubdate").text if @type == :rss | |
puts item.xpath("published").text if @type == :atom | |
puts | |
puts item.xpath("description").text.gsub("]]>", "") | |
if @verbosity == "full" and @type == :rss | |
puts | |
puts item.xpath("encoded").text.gsub("]]>", "") | |
end | |
80.times { print "-" } and print "\n" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment