der kl@mmeraffe | ruby. java. development.

a developers guide to the world of code

Friday, September 01, 2006

Simple Atom Feed With Ruby

Its really simple, took me bout an hour :-) But it suits my needs, and i don't have to implement other libs then build in (not even xml, allright, i'm crazy). Its not fast, reliable or something, but i wanted to create an atom feed that shows the files from a directory.
Heres the code:

class Atomfeed
attr_accessor :title, :subtitle, :link, :updated, :authorname, :authoremail, :id, :entries

def initialize
@title = ""
@subtitle = ""
@link = "http://"
@updated = ""
@authorname = ""
@authoremail = ""
@id = ""
@entries = []
end

def create_feed
@xml = ""
@xml = @xml + "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<feed xmlns=\"http://www.w3.org/2005/Atom\">\n"
@xml = @xml + "<title>" + @title + "</title>\n"
@xml = @xml + "<subtitle>"+@subtitle+"</subtitle>\n"
@xml = @xml + "<link href=\""+@link+"\"/>\n"
@xml = @xml + "<updated>"+@updated+"</updated>\n"
@xml = @xml + "<author>\n <name>"+@authorname+"</name>\n <email>"+@authoremail+"</email>\n </author>\n"
@xml = @xml + "<id>"+@id+"</id>\n"
@entries.each do |entry|
@xml = @xml + " <entry>\n"
@xml = @xml + " <title>"+entry.title+"</title>\n"
@xml = @xml + " <link href=\""+entry.link+"\"/>\n"
@xml = @xml + " <id>"+entry.id+"</id>\n"
@xml = @xml + " <updated>"+entry.updated+"</updated>\n"
@xml = @xml + " <summary>"+entry.summary+"</summary>\n"
@xml = @xml + " </entry>\n"
end
@xml = @xml + "</feed>"
end
end

class Entry
attr_accessor :title, :link, :id, :updated, :summary

def initialize
@title = ""
@link = "http://"
@id = ""
@updated = ""
@summary = ""
end
end


Thats it (Lots of stuff to refactor here, but - hey, it works). To use it, i just start a webrick httpserver and map an action to the create_feed method. Before that, i fill the Atomfeed / Entry objects:


require 'webrick'
include WEBrick

s = HTTPServer.new( :Port => 2000 )

class AtomServlet < HTTPServlet::AbstractServlet
def do_GET(req, res)
@directory = "c:\\dev"
Dir.chdir(@directory)
@files = Dir["*"]
feed = Atomfeed.new
feed.title = "New files"
feed.subtitle = "Yeah, new Files"
feed.updated = Time.now.to_s
feed.authorname = "dan"
feed.authoremail = "blub@nothing_here.com"
feed.id = "123456789"

@files.each do |file|
entry = Entry.new
entry.title = file.to_s
entry.link = "http://"+file.to_s
entry.id = file.to_s
entry.updated = "134"
entry.summary = "huuhu"
feed.entries.push(entry)
end

res.body = feed.create_feed
res['Content-Type'] = "text/html"
end
end

s.mount("/atom.xml", AtomServlet)
trap("INT"){ s.shutdown }
s.start



Most Information here doesn't make sense, but it shows all files in the working directory :-) ruby is so much fun!

add to del.icio.us | submit to digg | submit to reddit