These days, the free web APIs are multiplying like rabbits. Every hot new 2.0 application is providing a feature-rich API almost as soon as it launches. Most APIs are based around some form of XML exchange between client and server, whether that be with SOAP, XMLRPC, RSS, Atom, or some proprietary XML "protocol." It seems like there are more XML-over-HTTP flavors than there are in the Ben and Jerry's Flavor Graveyard. Anyway, in all of my recent mash-up fun, one thing that has remained constant is the speed and flexibility that ruby brings to the coding for these APIs.
Up until now, there hasn't been any one feature of ruby that stuck out as the reason it lends itself so readily to writing XML APIs. But this weekend, as I was writing a ruby Blogger module, I found the DelegateClass to be especially useful. Since the new API for Blogger is Google's GData, based on RSS and Atom, I've been able to leverage FeedTools extensively. In fact, my "library" will end up being no more than a few lines to wrap FeedTools' parsing and generation, thanks to ruby's delegate lib. For example:
class Entry < DelegateClass( FeedItem )
attr_accessor :edit_link, :self_link
def initialize(feed_item)
super(feed_item)
@edit_link = self.links.find { |l| l.rel == 'edit' }.href
@self_link = self.links.find { |l| l.rel == 'self' }.href
end
This example declares a class Entry which represents a blog entry. Since an entry in the GData API is just an Atom entry element, I'm able to delegate 99% of the functionality to the FeedItem class from FeedTools. Thanks to the power of delegation, I only have to define a few extra methods here and there to "Google-ize" the FeedTools objects.
Pretty cool!
Leave a Reply