Tagging my blog on Delicious

26 August 2010 Tagging my blog on Delicious

I've always thought that my blog posts could do with a bit of extra meta-data to make them easier to browse and categorize. Tagging is a simple way of doing that and Jekyll, the generator I use to create my blog supports basic tagging out of the box.

I wanted to go one step further, so, inspired by an idea of a former Reevoo colleague of mine, Chris Roos, I decided to tag all of posts on Delicious.

Automatically tagging posts in Delicious with Ruby

Of course, there's no way I'm going to sit here and tag all of my posts manually so I immediately looked into ways of automating it. As it turns out, it was quite simple.

The first step is loading up the Jekyll data model, which gives you access to all of your posts, and their attributes.

config = Jekyll.configuration('source' => path_to_site_root)
# read all blog data on load
site = Jekyll::Site.new(config).tap { |site| site.read } 

With access to the site object, you can iterate over all posts and for each post, access the tags collection (tags are stored as a space-separated list in your post's YAML front-matter).

The next step was getting the data into Delicious. The WWW::Delicious gem makes this simple with one caveat: if you have a newer Delicious account that uses the Yahoo authentication system, you need to use OAuth. See this blog post for more information.

With the Delicious API, it's simply a case of iterating over each post and creating a new bookmark on Delicious with the appropriate metadata and tags. In this example, I also see if a bookmark exists already; if it is I delete it and recreate it, ensuring any updated tags are reflected in the bookmark.

posts.each do |post|
  next if post.tags.empty?
  if @api.posts_get(:url => url_for_post(post), :tag => default_tag).any?
    :url   => url_for_post(post),
    :title => post.data['title'],
    :tags  => [post.tags, default_tag].flatten
  puts "➜ Tagged post '#{post.data['title']}'."

Additionally, I take all posts with a "default" tag of @lukeredpath.co.uk, so they are easily identifiable by my script.

This is all tied together by a simple wrapper script that supports options for tagging all posts, or just the last post. I run this (for only the last post) as part of my deployment Rake task to ensure my newest post is added.

The Github repository I use for my blog is private, but I've uploaded all of the code to this gist. The code is licensed under the "do whatever the hell you like with it" license. Have fun.