Using the Digg API with Ruby on Rails
July 12, 2007 – 3:01 amThe following tutorial will get you started fast using the Digg API in your Ruby on Rails (RoR) application. I am assuming you already have setup your RoR application.
Note: At the end of the post I make the code available in a text file, please excuse the wordpress formatting… its not good
This tutorial will cover grabbing your most recent submitted articles and displaying the title and number of diggs in a list. With this code you can easily expand to grab any data you wish using the Digg API.
In your template you will need to make the following includes:
<% require 'open-uri' require 'rexml/document' %>
open-uri will be used to grab the data from Digg and rexml will be used to parse the obtained xml data.
The next issue is to grab the data you need. In this case, I will grab the last 20 articles I have submitted ( a complete list of data to be grabbed is here.):
<%
response =
open("http://services.digg.com/user/[username]/submissions?
appkey=http%3A%2F%2Fthembid.com&type=xml&count=20", "User-Agent" => "Demo/0.1").read
%>
I split the above to three lines, because of the formatting, it should be one line. At the end of this post is a link to a text file with the proper formatting.
username
is your digg username.
appkey
is described here.
type
can be XML, JSON, javascript or PHP. Details are here.
count
determines how many data entries are retrieved. You can read more about arguments (like count) here.
Now that you have the XML stored in the response variable it’s time to use Ruby’s built in XML parser to grab the data you need.
Note that you can put the URI in the open function in your browser to see the full schema of the returned XML and make sure the data you want is retrieved.
The following code creates a new REXML object:
doc = REXML::Document.new(response)
Now lets grab the title (this is an example of retrieving a tag value):
titles = []
doc.elements.each("stories/story/title") { |element|
titles << element.text
}
Now lets grab the number of diggs (this is an example of retrieving an attribute):
diggs = []
doc.elements.each("stories/story") { |element|
diggs << element.attributes["diggs"]
}
Let’s now print out our title and number of diggs in a list:
<% count = 0
while count < 20
%>
<%= titles[count] %> (Diggs: <%= diggs[count] %>)
<%
count += 1
end
%>
That’s it! With these simple instructions you can get, store and display all the data you need to create your next killer Digg API application in Ruby on Rails.
You can download the code in a text file here.
7 Responses to “Using the Digg API with Ruby on Rails”
Perhaps it would be better to combine the story and diggs into one loop:
stories = {}
doc.elements.each(”stories/story”) { |story|
title = story.get_elements(”title”).first.text
stories[title]=story.attributes["diggs"]
}
By Mark Thomas on Jul 12, 2007
Mark,
That is a good way to do it. Thanks!
By ethomas on Jul 12, 2007