Pages

Friday, May 21, 2010

How to create RSS Feed using Ruby

To create an RSS Feed from Ruby. You can use the code below:
--- code starts here---
require 'rss/maker'

version = "2.0" # ["0.9", "1.0", "2.0"]
destination = "test_maker.xml" # local file to write

content = RSS::Maker.make(version) do |m|
m.channel.title = "Example Ruby RSS feed"
m.channel.link = "http://www.rubyrss.com"
m.channel.description = "Old news (or new olds) at Ruby RSS"
m.items.do_sort = true # sort items by date

i = m.items.new_item
i.title = "Ruby can parse RSS feeds"
i.link = "http://www.rubyrss.com/"
i.date = Time.parse("2007/2/11 14:01")

i = m.items.new_item
i.title = "Ruby can create RSS feeds"
i.link = "http://www.rubyrss.com/"
i.date = Time.now
end

File.open(destination,"w") do |f|
f.write(content)
end
--- code end here ---
from rubyrss.com

Modify the script abit so you can query from your database to your xml!
--code starts here ---
require 'rss/maker'
require 'rubygems'
require 'mysql'


begin

dbh = Mysql.real_connect('127.0.0.1', 'yourusername', 'yourpassword', 'yourdatabase', 3306)
#this is the mysql connection part start

query = dbh.query('select id,name from student') #your database query

version = "2.0" # ["0.9", "1.0", "2.0"]
destination = "test_maker.xml" # local file to write

content = RSS::Maker.make(version) do |m|
m.channel.title = "Welcome to my RSS Maker Example"
m.channel.link = "http://www.yourwebsites.com "
m.channel.description = "Student Listing RSS"
m.items.do_sort = true # sort items by date


query.each do |data|
#loop through your query and put it into the xml, data[0] = id and data[1] = name
i = m.items.new_item
i.title = "#{data[0]} "
i.link = "#{data[0]}"
i.date = Time.parse("#{data[1]}")
i.description = "student id : #{data[0]} student name: #{data[1]}"
end


end

File.open(destination,"w") do |f|
f.write(content)
end

rescue MysqlError => e
print "Error code: ", e.errno, "\n"
print "Error message: ", e.error, "\n"

ensure
query.free #free query data
dbh.close #close the connection

end
---code end here ---

The code is pretty straight forward. You just need to connect to your database and loop through all the data that you want to put in your xml file. Using Mysql.real_connect.

No comments:

Post a Comment